﻿/* 12-09-2008 */

var MVHome = {
    Load: function() {
        MVHome.HackForAnchorTag();
    },
    Init: function() {
        MVHome.DropDownMenus();
        MVHome.Search();
        MVHome.WelcomeBox();
        MVHome.Tabs();
        MVHome.AddAlert();
        MVHome.VideoStoryTip();
        MVHome.InitFontSize();
        MVHome.CopyBox();
        MVHome.InitLettersToEditorForm();
        MVHome.ToggleArticleSidebar();
        MVHome.InteractiveEmbedLB.init();
        MVHome.EmailFromInteractive.init();

    },
    CopyBox: function() {
        var eles = $$('.copyBox');
        eles.each(function(ele) {
            ele.__STATIC_TEXT = ele.value;

            ele.addEvent('change', function() {
                this.valueOf = this.__STATIC_TEXT;
            });

            ele.addEvent('click', function() {
                this.valueOf = this.__STATIC_TEXT;
                this.select();
            });
        });
    },
    InitCharCount: function(options) {
        window.addEvent('domready', function() {
            if (!options.maxLength) { options.maxLength = 300; }
            options.field.addEvent('keyup', function() {
                if (options.field.value.length < options.maxLength) {
                    if (options.countSpan != null) {
                        options.countSpan.set('class', '');
                        options.maxMessageSpan.set('class', 'hidden');
                    }
                    options.counter.set('text', options.maxLength - options.field.value.length);
                }
                else {
                    options.field.value = options.field.value.slice(0, options.maxLength);
                    if (options.countSpan != null) {
                        options.countSpan.set('class', 'hidden');
                        options.maxMessageSpan.set('class', '');
                    }
                    else {
                        options.field.value = options.field.value.substr(0, options.maxLength);
                        options.counter.set('text', '0');
                    }
                }
            });
            options.counter.set('text', options.maxLength);
        });
    },
    InitCharCountLetters: function(options) {
        window.addEvent('domready', function() {
            if (!options.maxLength) { options.maxLength = 300; }
            options.field.addEvent('keyup', function() {
                if (options.field.value.length < options.maxLength) {
                    if (options.countSpan != null) {
                        options.countSpan.set('class', '');
                        options.maxMessageSpan.set('class', 'hidden');
                    }
                    options.counter.set('text', options.maxLength - options.field.value.length);
                }
                else {
                    options.field.value = options.field.value.slice(0, options.maxLength);
                    if (options.countSpan != null) {
                        options.countSpan.set('class', 'hidden');
                        options.maxMessageSpan.set('class', '');
                    }
                    else {
                        options.field.value = options.field.value.substr(0, options.maxLength);
                        options.counter.set('text', '0');
                    }
                }
            });
            options.counter.set('text', options.maxLength);
        });
    },
    InitCharCountVideo: function(options) {
        window.addEvent('domready', function() {
            if (!options.maxLength) { options.maxLength = 300; }
            options.field.addEvent('keyup', function() {
                if (options.field.value.length < options.maxLength) {
                    if (options.countSpan != null) {
                        options.countSpan.set('class', '');
                        options.maxMessageSpan.set('class', 'hidden');
                    }
                    options.counter.set('text', options.maxLength - options.field.value.length);
                }
                else {
                    options.field.value = options.field.value.slice(0, options.maxLength);
                    if (options.countSpan != null) {
                        options.countSpan.set('class', 'hidden');
                        options.maxMessageSpan.set('class', '');
                    }
                    else {
                        options.field.value = options.field.value.substr(0, options.maxLength);
                        options.counter.set('text', '0');
                    }
                }
            });
            options.counter.set('text', options.maxLength);
        });
    },

    InitEmailForm: function(formId, linkId) {
        if (!MVHome.__EMAIL_FORM) {
            MVHome.__EMAIL_FORM = [];

            window.addEvent('domready', function() {
                MVHome.__EMAIL_FORM.each(function(options) {
                    var ele = $(options.formId);
                    var linkEle = $(options.linkId);
                    $('message').value = '';

                    MVHome.InitCharCount({
                        field: $('message'),
                        counter: ele.getElement('.characterCount'),
                        maxLength: MVHome.__EMAIL_FORM_MAX_LENGTH,
                        countSpan: $('emailMessageCount'),
                        maxMessageSpan: $('emailMaxMessage')
                    });

                    var form = ele.getElement('.emailForm');
                    var thankYou = ele.getElement('.thankYou');

                    linkEle.addEvent('click', function() {
                        form.removeClass('hidden');
                        thankYou.addClass('hidden');
                        $('sendCopy').checked = false;
                        //$('message').value = '';
                    });

                    form.getElement('.submitButton').addEvent('click', function() {
                        var errorEle = ele.getElement('.errorContainer');
                        var emailsEle = ele.getElement('.emailedRecipients');
                        var msgField = $('message').value;
                        var msgSubject = $('subject').value;
                        var msgRecipientEmail = $('recipientEmailAddresses').value;
                        var msgEmail = $(MVHome.__EMAIL_ADDRESS).value;
                        var sendCopy = $('sendCopy').checked;

                        if (msgField.length > MVHome.__EMAIL_FORM_MAX_LENGTH) {
                            alert("You are currently over your maximum limit. The maximum limit is " + MVHome.__EMAIL_FORM_MAX_LENGTH + " and you have " + msgField.length);
                        } else {
                            errorEle.addClass('hidden');
                            var jsonObj = {
                                email: msgEmail,
                                recipientEmail: msgRecipientEmail,
                                message: msgField,
                                subject: msgSubject,
                                sendCopy: sendCopy,
                                localeId: MVHome.__LOCALE_ID,
                                articleId: MVHome.__ARTICLE_ID
                            };

                            new Request({
                                'url': '/Webservice/ArticleTools.asmx/ProcessEmailThisArticle',
                                'headers': { 'Content-type': 'application/json' },
                                'urlEncoded': false,
                                'onComplete': function(str) {
                                    var myObj = JSON.decode(str).d;
                                    if (myObj.error) {
                                        errorEle.empty();
                                        myObj.error.each(function(msg) {
                                            errorEle.adopt(
												new Element('li').set('html', msg)
											);
                                        });
                                        errorEle.removeClass('hidden');
                                    } else if (myObj.emails) {
                                        emailsEle.empty();
                                        myObj.emails.each(function(msg) {
                                            emailsEle.adopt(
												new Element('li').set('html', msg)
											);
                                        });
                                        emailsEle.removeClass('hidden');
                                        form.addClass('hidden');
                                        thankYou.removeClass('hidden');

                                        $('sendCopy').checked = false;
                                        $('message').value = '';
                                        $('recipientEmailAddresses').value = '';
                                        //$('emailAddress').value = '';
                                    }
                                }
                            }).send(JSON.encode(jsonObj));
                        }
                    });
                });
            });
        }

        MVHome.__EMAIL_FORM.push({ formId: formId, linkId: linkId });
    },
    InitLettersToEditorForm: function() {
        if ($('lettersContainer')) {
            MVHome.__LTTE_TEXT_AREA = $(MVHome.__LTTE_TEXT_AREA);
            var letters = $('lettersContainer');
            var form = $('submitLetter');
            var showMore = $('moreLetters');
            var linkEle = $('submitLetterLink');
            var letterPreview = $$('.letterPreview');
            var thankYou = $('letterConfirm');
            var confirmMessage = $('letterSubmitConfirm');

            var closeForm = function() {
                form.fade('out').addClass('hidden');
                letters.removeClass('hidden').fade('in');
                backtoList.addClass("hidden");
            };

            //If there are letters, activate close box, else hide it
            var backtoList = $$("div.lettersToEditorInner > h3 > a.close");
            if (MVHome.__LTTE_HAS_LETTERS) {
                backtoList.setProperty('href', 'javascript:Void()')
                  .addEvent("click", function() { closeForm(); });
            }
            else { backtoList.destroy(); }

            MVHome.InitCharCountLetters({
                field: MVHome.__LTTE_TEXT_AREA,
                counter: form.getElement('.characterCount'),
                maxLength: MVHome.__LTTE_FORM_MAX_LENGTH,
                countSpan: $('ltteMessageCount'),
                maxMessageSpan: $('ltteMaxMessage')
            });

            if (showMore != null) {
                showMore.setProperty('href', 'javascript:Void()');
                showMore.addEvent('click', function() {
                    $('moreResults').removeClass('hidden');
                    showMore.addClass('hidden');
                });
            }

            linkEle.setProperty('href', 'javascript:Void()');
            linkEle.addEvent('click', function() {
                //reset preview / confirm blocks
                letterPreview.fade('in').removeClass('hidden');
                thankYou.fade('out').addClass('hidden');
                //hide letters
                letters.fade('out').addClass('hidden');
                //show form
                form.setStyle('opacity', '0').removeClass('hidden').fade('in').setStyle('width', '100%');
                //show close button
                if (backtoList) backtoList.removeClass("hidden");
            });

            // If no letters, show submit letter box
            if (!MVHome.__LTTE_HAS_LETTERS) {
                linkEle.fireEvent("click");

            }

            var ltteLB = $$(".letterPreview"),
             closeLB = function() {
                 ltteLB.getParent(".lightboxWindow").getElement("a.close").fireEvent("click");
             }

            // Allow "edit message" to close lightbox
            ltteLB.getElement("p.close a").addEvent("click", closeLB);

            //
            // Process preview
            $("ltteSubmitButton").addEvent("click", function() {

                // Hacked-in validate    
                (function() {
                    var errorEle = form.getElement('.ltteErrorContainer');
                    var firstName = $('ltteFirstName').value;
                    var lastName = $('ltteLastName').value;
                    var company = $('ltteCompany').value;
                    var userTitle = $('ltteTitle').value;
                    var msgEmail = $('ltteEmail').value;
                    var userLocation = $('ltteLocation').value;
                    var msgField = MVHome.__LTTE_TEXT_AREA.value;

                    if (msgField.length > MVHome.__LTTE_FORM_MAX_LENGTH) {
                        alert("You are currently over your maximum limit. The maximum limit is " + MVHome.__LTTE_FORM_MAX_LENGTH + " and you have " + msgField.length);
                    }
                    else {
                        errorEle.addClass('hidden');
                        var jsonObj = {
                            firstName: firstName,
                            lastName: lastName,
                            company: company,
                            userTitle: userTitle,
                            email: msgEmail,
                            userLocation: userLocation,
                            message: msgField,
                            articleNumber: s_prop4
                        };

                        new Request({
                            'url': '/WebService/LetterToTheEditor.asmx/ValidateLetter',
                            'headers': { 'Content-type': 'application/json' },
                            'urlEncoded': false,
                            'onComplete': function(str) {
                                var myObj = JSON.decode(str).d;
                                if (myObj.success == 'False') {
                                    errorEle.empty();
                                    errorEle.adopt(
   				   new Element('li').set('html', myObj.message)
   			   );
                                    errorEle.removeClass('hidden');

                                } else {


                                    var lightboxOpener = $$(".previewLetter"),
                   ltteLB = $$(".letterPreview"),
                   updateFields = {
                       subjectField: ltteLB.getElement("div.letterTitle"),
                       messageField: ltteLB.getElement("div.letterBody")
                   },
                   params = {},
                   subject = form.getElement("p.subject").clone();

                                    // Process the form fields for previewing
                                    subject.getElement("strong").destroy();
                                    params = {
                                        subject: subject.get("text").trim(),
                                        message: MVHome.__LTTE_TEXT_AREA.value.replace(/(\r\n|[\r\n])/g, "<br />")
                                    };

                                    params.subject = "Re: " + params.subject;   //RS: prepended the subject with Re: 

                                    // Update the preview
                                    updateFields.subjectField.set("text", params.subject);
                                    updateFields.messageField[0].innerHTML = params.message;

                                    // Open lightbox
                                    lightboxOpener.fireEvent("click");

                                }
                            }
                        }).send(JSON.encode(jsonObj));
                    }
                })();

                var confirmSubmission = $("ltteConfSubmitButton");
                //clear click event since this is generated on every open
                confirmSubmission.removeEvents("click");
                // confirm submission validates fields and submits on success
                // ( else hides lightbox and returns error state )
                confirmSubmission.addEvent('click', function() {
                    var errorEle = form.getElement('.ltteErrorContainer');
                    var firstName = $('ltteFirstName').value;
                    var lastName = $('ltteLastName').value;
                    var company = $('ltteCompany').value;
                    var userTitle = $('ltteTitle').value;
                    var msgEmail = $('ltteEmail').value;
                    var userLocation = $('ltteLocation').value;
                    var msgField = MVHome.__LTTE_TEXT_AREA.value;
                    var ltteLB = $$(".letterPreview");
                    var closeLB = function() {
                        ltteLB.getParent(".lightboxWindow").getElement("a.close").fireEvent("click");
                    }

                    // Allow "edit message" to close lightbox
                    ltteLB.getElement("p.close a").addEvent("click", closeLB);
                    if (msgField.length > MVHome.__LTTE_FORM_MAX_LENGTH) {
                        alert("You are currently over your maximum limit. The maximum limit is " + MVHome.__LTTE_FORM_MAX_LENGTH + " and you have " + msgField.length);
                    } else {
                        errorEle.addClass('hidden');
                        var jsonObj = {
                            firstName: firstName,
                            lastName: lastName,
                            company: company,
                            userTitle: userTitle,
                            email: msgEmail,
                            userLocation: userLocation,
                            message: msgField,
                            articleNumber: s_prop4
                        };

                        new Request({
                            'url': '/WebService/LetterToTheEditor.asmx/SubmitLetter',
                            'headers': { 'Content-type': 'application/json' },
                            'urlEncoded': false,
                            'onComplete': function(str) {
                                var myObj = JSON.decode(str).d;
                                if (myObj.success == 'False') {
                                    errorEle.empty();
                                    errorEle.adopt(
									   new Element('li').set('html', myObj.message)
								   );
                                    errorEle.removeClass('hidden');
                                    closeLB();

                                } else {
                                    //if there are letters, open the list
                                    if (MVHome.__LTTE_HAS_LETTERS) {
                                        form.fade('out').addClass('hidden');
                                        letters.removeClass('hidden').fade('in');
                                    }
                                    ltteLB.fade('out').addClass('hidden');

                                    // display confirmation
                                    confirmMessage.set('html', myObj.message)
                                    thankYou.setStyle('opacity', '0').removeClass('hidden').fade('in');
                                    if (backtoList) backtoList.addClass("hidden");

                                    // reset message field (other field values should be kept in case the user wants to write another letter)
                                    MVHome.__LTTE_TEXT_AREA.value = '';

                                }
                            }
                        }).send(JSON.encode(jsonObj));
                    }
                });


            });
        }
    },
    InitFontSize: function() {
        if (MVHome.__TEXT_SIZE_ID) {
            var fontClassNames = ['normalStory', 'largeStory', 'largestStory'];
            var ele = $(MVHome.__TEXT_SIZE_ID);
            var mainEle = ele.getElement('a');
            var chooser = ele.getElement('.chooseSize');

            mainEle.addEvent('mouseenter', function() {
                chooser.removeClass('hidden');
            });

            ele.addEvent('mouseleave', function() {
                chooser.addClass('hidden');
            });

            var fontEles = chooser.getElements('a'),
			    storyContent = $$(".storyContent");

            fontEles.setProperty('href', 'javascript:Void()');

            fontEles.addEvent('click', function() {
                fontClassNames.each(function(cssClass) {
                    storyContent.removeClass(cssClass);
                });
                var currentSize = fontEles.indexOf(this);
                storyContent.addClass(fontClassNames[currentSize]);
                chooser.getElements('a').removeClass('active');
                this.addClass('active');
                this.blur();
                Cookie.write('fontSize', currentSize);
            });

            var storedSize = Cookie.read('fontSize');
            if (storedSize != null) {
                storyContent.addClass(fontClassNames[storedSize]);
            }
        }
    },
    HackForAnchorTag: function() {
        if (location.href.indexOf("#") != -1) {
            //console.log("done");
            location.href = location.href;
        }
    },
    AddAlert: function() {
        if (MVHome.__ADD_ALERT_LINK) {
            addAlertEle = $(MVHome.__ADD_ALERT_LINK);
            addAlertText = $(MVHome.__ADD_ALERT_TEXT);
            if (addAlertEle && !addAlertEle.hasClass('disabled')) {
                addAlertEle.addEvent('click', function() {
                    addAlertTextEle = $('AddToAlerts');
                    addAlertTextEle.set('html', 'Please Wait');
                    addAlertTextEle.addClass('showLoading');
                    var jsonPost = { categoryId: MVHome.__CURRENT_L2_ID.toInt() };

                    var myAjax = new Request({
                        url: '/webservice/ArticleTools.asmx/ProcessAddToAlert',
                        method: 'post',
                        urlEncoded: false,
                        headers: { 'Content-type': 'application/json' },
                        onComplete: function(e) {
                            var obj = JSON.decode(e).d;
                            addAlertTextEle.set('html', obj);
                            addAlertTextEle.removeClass('showLoading');
                            var obj = JSON.decode(e).d;
                            addAlertEle.addClass('disabled');
                            addAlertEle.style.display = 'none';
                            addAlertText.style.display = 'inline';
                            var closeLink = addAlertTextEle.getParent().getParent().getParent().getElement('a.close');
                            //setTimeout( function() { closeLink.fireEvent('click') }, 5000 );				
                        }
                    }).send(JSON.encode(jsonPost));
                });
            }
        }
    },
    Tabs: function() {
        $$('.tabContainer').each(function(ele) {
            var tabContent = ele.getElements('.tabContent');
            var tabs = ele.getElements('.tabNavContainer a');

            if (tabs.length != tabContent.length) {
                // TODO: HIDDEN ERROR HANDLING
            }

            tabContent.each(function(ele) {
                if (!ele.hasClass('active')) {
                    ele.addClass('hidden');
                }
            });

            tabs.setProperty('href', 'javascript:Void()');
            tabs.addEvent('click', function() {
                currentTab = tabs.indexOf(this);
                tabs.getParent().removeClass('active');
                tabContent.removeClass('active').addClass('hidden');
                this.getParent().addClass('active');
                tabContent[currentTab].addClass('active').removeClass('hidden');
                this.blur();
            });

        });
    },
    Search: function() {
        MVHome.__SEARCH_BOX = $(MVHome.__SEARCH_BOX);
        if (MVHome.__SEARCH_BOX) {
            var textbox = MVHome.__SEARCH_BOX.getElement('input.text');
            var button = MVHome.__SEARCH_BOX.getElement('input.button');

            if (textbox && button) {
                textbox.addEvents({
                    'focus': function() {
                        button.setAttribute('src', Settings.Search.Button.On);
                    },
                    'blur': function() {
                        button.setAttribute('src', Settings.Search.Button.Off);
                    }
                });

                button.addEvents({
                    'mouseenter': function() {
                        button.__OLD = button.getAttribute('src');
                        button.setAttribute('src', Settings.Search.Button.Over);
                    },
                    'mouseout': function() {
                        if (button.__OLD) {
                            button.setAttribute('src', button.__OLD);
                        } else {
                            button.setAttribute('src', Settings.Search.Button.Off);
                        }

                        button.__OLD = null;
                    }
                });
                // Patch to blur if page loads with search box focused
                window.setTimeout(function() { MVHome.__SEARCH_BOX.getElement('input.text').blur() }, 10)
            }

        }
    },
    DropDownMenus: function() {
        var MenuEle = $('MainNav');
        if (MenuEle) {

            // hide/show form fields that reach too close to the sun
            var Fields = function(action) {
                if (!(MVHome.__CONTROLS_TO_HIDE && MVHome.__CONTROLS_TO_HIDE.length)) { return false; }
                var arrFields = MVHome.__CONTROLS_TO_HIDE;

                switch (action) {
                    case "show":
                        $each(arrFields, function(id) { $(id).setStyle("visibility", "visible"); });
                        break;
                    case "hide":
                        $each(arrFields, function(id) { $(id).setStyle("visibility", "hidden"); });
                        break;
                }
                return this;
            }

            MenuEle.getElements('li.mainMenu').each(function(ele) {
                ele.getElement('a').href = Settings.VOID_LINK;
                ele.subMenu = ele.getElement('.subMenu');
                ele.content = ele.getElement('.subMenu .shadow-Content div');

                var myFx = new Fx.Tween(ele.subMenu, { duration: 50 });

                ele.addEvent('mouseenter', function() {
                    Fields("hide");
                    this.subMenu.setStyle('opacity', '0');
                    this.addClass('on');

                    // fading in the text separately doesn't really work well in IE
                    if (!Browser.Engine.trident) {
                        ele.content.setStyle('opacity', '0');
                        setTimeout(function() {
                            new Fx.Tween(ele.content, { duration: 150 }).start('opacity', '1');
                        }, 150
                        );
                    }

                    myFx.start('opacity', '1');
                });

                ele.addEvent('mouseleave', function() {
                    Fields("show");
                    ele.removeClass.bind(ele, ['on'])();
                });
            });
        };
    },
    WelcomeBox: function() {
        MVHome.__WELCOME_BOX = $(MVHome.__WELCOME_BOX);
        //NOTE: the login_visitor_link is only present when the user is a visitor
        MVHome.__LOGIN_VISITOR_LINK = $(MVHome.__LOGIN_VISITOR_LINK);

        if (MVHome.__WELCOME_BOX) {
            var closedBox = MVHome.__WELCOME_BOX.getElement('.welcomeBoxClosedInner');
            var openedBox = MVHome.__WELCOME_BOX.getElement('.welcomeBoxOpen');

            //var editionType = MVHome.__WELCOME_BOX.getElement('.editionType');
            var openLink = closedBox.getElement('a.openWelcomeBox').VoidLink();
            var openLink2;

            //if visitor, then set setup the onclick (here and below)
            if (MVHome.__LOGIN_VISITOR_LINK)
                openLink2 = MVHome.__LOGIN_VISITOR_LINK.VoidLink();
            var closeLink = openedBox.getElement('a.closeWelcomeBox').VoidLink();

            var mainAnimationEle = new Element('div', {
                'class': 'fakeAnimation clearfix hidden'
            }).adopt(
           	    new Element('div', {
           	        'class': 'fakeAnimationInner'
           	    }).adopt(
           	        new Element('div', {
           	            'class': 'fakeAnimationTopLeft'
           	        }).adopt(
           	            new Element('div', {
           	                'class': 'fakeAnimationTopRight'
           	            }).adopt(
           	                new Element('div', {
           	                    'class': 'fakeAnimationBottomLeft'
           	                }).adopt(
           	                    animationEle = new Element('div', {
           	                        'class': 'fakeAnimationBottomRight'
           	                    })
           	                )
           	            )
           	        )
           	    )
           	).inject(closedBox.getParent(), 'after');

            //same function used for both the [+] link and the Login button when the user is a visitor
            var openFunction = function() {
                var newFx = new Fx.Morph(animationEle, {
                    'duration': 500,
                    'transition': Fx.Transitions.Expo.easeInOut,
                    'events': {
                        'complete': function() {
                            mainAnimationEle.Hide();
                            closedBox.getParent().Show();
                        }
                    }
                });

                Cookie.write("welcomeBoxState", "open", { path: "/" });
                // editionType.Hide();
                var openedSize = openedBox.getRealSize();
                var closedSize = closedBox.getRealSize(1);

                closedBox.getParent().Hide();
                openedBox.Hide();

                animationEle.setStyles({
                    'height': closedSize.y,
                    'width': closedSize.x
                });

                mainAnimationEle.Show();

                newFx.addEvent('complete', function() {
                    mainAnimationEle.Hide();
                    openedBox.Show();
                });

                newFx.start({
                    'height': openedSize.y,
                    'width': openedSize.x
                });
            };

            openLink.addEvent('click', openFunction);

            //if visitor, then set setup the onclick (here and above)
            if (MVHome.__LOGIN_VISITOR_LINK != null)
                openLink2.addEvent('click', openFunction);

            closeLink.addEvent('click', function() {
                var newFx = new Fx.Morph(animationEle, {
                    'duration': 500,
                    'transition': Fx.Transitions.Expo.easeInOut,
                    'onComplete': function() {
                        mainAnimationEle.Hide();
                        closedBox.getParent().Show();
                    }
                });

                Cookie.write("welcomeBoxState", "closed", { path: "/" });

                var openedSize = openedBox.getRealSize();
                var closedSize = closedBox.getRealSize(1);
                closedBox.getParent().Hide();
                openedBox.Hide();

                animationEle.setStyles({
                    'height': openedSize.y,
                    'width': openedSize.x
                });

                mainAnimationEle.Show();

                newFx.start({
                    'height': closedSize.y,
                    'width': closedSize.x
                });
            });
        }
    },

    ToggleArticleSidebar: function() {
        $$('.sideBar').each(function(ele) {
            var toggleLink = ele.getElement('a.toggleState').VoidLink();
            var sidebarHTML = ele.getElement('.sideBarHtmlBody');

            toggleLink.addEvent('click', function() {
                this.getParent('.sideBar').toggleClass('sideBarOpen');
            });
        });
    },
    JumpToAndOpenSidebar: function(id) {
        var jumpPoint = id,
            posY = $(id).getCoordinates().top;
        if (!$(id)) { return; }
        if (arguments.length > 1 && typeof arguments[1] == "string") { jumpPoint = arguments[1]; }
        $(id).addClass("sideBarOpen");
        window.location.href = window.location.href.replace(/\#?(\S)+$/, "#" + jumpPoint);
        window.scroll(0, posY);
    },

    InteractiveEmbedLB: {
        init: function() {
            this.lightboxOpener = $$("body").getElement(".triggerEmbedLB");
            this.lightbox = $$("body").getElement("div[id*=embedLB]");
            if (this.lightboxOpener[0] == null) { return false; }
            /*
            this.lightboxOpener.setProperty("href", "javascript:void(0);")
            LightBox.Add({
            LightBoxId: $$("body").getElement("div[id*=embedLB]").getProperty("id"),
            LinkId: this.lightboxOpener.getProperty("id")
            });
            */
            this.lightboxContent = $$("body").getElement(".embedHTML");
            this.textarea = this.lightboxContent.getElement("textarea")
            this.textarea.addEvent("focus", function() { this.select(); this.fireEvent("blur"); });
            return this;
        },
        getEmbedHTML: function(rootURL, assetID, localeID) {
            var htmlTemplate = '' +
            '<object width="428" height="338">\n' +
               '\t<param name="movie" value="$rootURL$App_Themes/v2.0/swf/external_player.swf">\n' +
               '\t<param name="flashvars" value="assetsPath=$rootURL$App_Themes/v2.0/swf/&amp;xmlFileName=$rootURL$xmlresources/videol2XML.aspx?assetid=$assetID$%26localeid=$localeID$">\n' +
               '\t<embed src="$rootURL$App_Themes/v2.0/swf/external_player.swf" width="428" height="338" flashvars="assetsPath=$rootURL$App_Themes/v2.0/swf/&amp;xmlFileName=$rootURL$xmlresources/videol2XML.aspx?assetid=$assetID$%26localeid=$localeID$">\n' +
               '\t</embed>\n' +
            '</object>\n';

            return htmlTemplate.replace(/\$rootURL\$/g, rootURL)
                            .replace(/\$assetID\$/g, assetID)
                            .replace(/\$localeID\$/g, localeID);
        },
        openLB: function() {
            this.lightbox.FadeIn();
            //this.lightboxOpener.fireEvent("click");
        },
        replaceTextareaText: function(rootURL, assetID, localeID) {
            this.textarea[0].value = this.getEmbedHTML(rootURL, assetID, localeID);
        },
        open: function(rootURL, assetID, localeID) {
            this.replaceTextareaText(rootURL, assetID, localeID);
            this.openLB();
        }
    },

    EmailFromInteractive: {
        init: function() {
            this.lightboxOpener = $$("body").getElement("a.triggerEmailVideoLB");
            if (this.lightboxOpener[0] == null) { return false; }

            this.grabElements();

            this.formSubmit.addEvent("click", function(e) {
                e.stop();
                MVHome.EmailFromInteractive.send();
            });
            /*
            this.lightboxOpener.setProperty("href", "javascript:void(0);")
            LightBox.Add({
            LightBoxId: $$("body").getElement("div[id*=emailVideoLB]").getProperty("id"),
            LinkId:this.lightboxOpener.getProperty("id")
            });
            */
            //do not clear this since otherwise the watermark is lost: this.formMessage[0].value = "";
            MVHome.InitCharCountVideo({
                field: this.formMessage[0],
                counter: $('emailMessageCountVideo').getElement('.characterCount'),
                maxLength: MVHome.__INTERACTIVE_EMAIL_FORM_MAX_LENGTH,
                countSpan: $('emailMessageCountVideo'),
                maxMessageSpan: $('emailMaxMessage')
            });

            return this;
        },
        grabElements: function() {
            this.lightboxOpener = $$("body").getElement("a.triggerEmailVideoLB");
            this.lightbox = $$("body").getElement("div[id*=emailVideoLB]");
            this.lightboxContent = $$("body").getElement("div.EmailFromInteractive");
            this.errorContainer = this.lightboxContent.getElement("ul.errorContainer");
            this.form = this.lightboxContent.getElement(".formContainer");
            this.storyDate = this.form.getElement("p.date");
            this.storyTitle = this.form.getElement("div.title");
            this.storyDek = this.form.getElement("p.dek");
            this.formSubject = this.form.getElement("input.email-subject");
            this.formSubmit = this.form.getElement("input.submitButton");
            this.formFromEmail = this.form.getElement("input.email-fromAddress");
            this.formToEmail = this.form.getElement("input.email-toAddress");
            this.formSubject = this.form.getElement("input.email-subject");
            this.formSendCopy = this.form.getElement("input.checkbox");
            this.formMessage = this.form.getElement("textarea.email-message");
            this.thanks = this.lightboxContent.getElement(".thankYou");
        },
        openLB: function() {
            this.lightbox.FadeIn();
            //this.lightboxOpener.fireEvent("click");
        },
        open: function(deepLinkID, emailTitle, emailSubject, date, title, description) {
            this.deepLinkID = deepLinkID;
            this.reset();
            this.generateEmailFields(emailTitle, emailSubject, date, title, description);
            this.openLB();
        },
        showForm: function() {
            this.form.removeClass("hidden");
            this.thanks.addClass("hidden");
        },
        showThanks: function() {
            this.thanks.removeClass("hidden");
            this.form.addClass("hidden");
        },
        reset: function() {
            this.showForm();
        },
        generateEmailFields: function(emailTitle, emailSubject, date, title, description) {
            this.storyDate.set("text", date);
            this.storyTitle.set("text", title);
            this.storyDek.set("text", description);
            this.formSubject[0].value = emailSubject;
        },
        send: function() {
            this.errorContainer.addClass("hidden");
            //{email, recipientEmail, subject, message, sendCopy, videoId}
            var jsonObj = {
                email: this.formFromEmail[0].value,
                recipientEmail: this.formToEmail[0].value,
                message: this.formMessage[0].value,
                subject: this.formSubject[0].value,
                sendCopy: this.formSendCopy[0].checked ? "True" : "False",
                videoId: this.deepLinkID
            }
            new Request({
                'url': '/webservice/Video.asmx/EmailVideo',
                'headers': { 'Content-type': 'application/json' },
                'urlEncoded': false,
                'onComplete': function(str) {
                    var message = JSON.decode(str).d;
                    if (message.success == "False") {
                        MVHome.EmailFromInteractive.errorContainer[0].empty();
                        MVHome.EmailFromInteractive.errorContainer.adopt(new Element('li').set('html', message.message));
                        MVHome.EmailFromInteractive.errorContainer.removeClass('hidden');
                    }
                    else if (message.success == "True") {
                        MVHome.EmailFromInteractive.errorContainer[0].empty();
                        MVHome.EmailFromInteractive.showThanks();
                        MVHome.EmailFromInteractive.thanks.getElement("div.message-success")[0].innerHTML = message.message;
                        //clear the textarea message, in case the user wants to re-send
                        $('ctl00_ctrlVideoPlayerOverlay_emailVideoLB_textArea').value = '';
                    }
                }
            }).send(JSON.encode(jsonObj));
        }
    },

    InsertAudio: function(mp3Url, width, clientId) {
        var so;
        if (width == "310") {
            so = new SWFObject("/App_Themes/v2.0/swf/mp3player_large.swf", "audioplayer" + clientId, "310", "28", "9", "#FFFFFF");
        } else if (width == "192") {
            so = new SWFObject("/App_Themes/v2.0/swf/mp3player_medium.swf", "audioplayer" + clientId, "192", "28", "9", "#FFFFFF");
        } else {
            so = new SWFObject("/App_Themes/v2.0/swf/mp3player_small.swf", "audioplayer" + clientId, "154", "28", "9", "#FFFFFF");
        }
        so.addParam("allowscriptaccess", "always");
        so.addParam("wmode", "transparent");
        so.addVariable("assetsPath", "/App_Themes/v2.0/swf/");
        so.addVariable("mp3path", mp3Url);
        so.addVariable("barWidth", (width / 310));
        so.write(clientId);

        eval("window.audioplayer" + clientId + " = document.getElementById('audioplayer" + clientId + "')");
    },

    InsertVideoPlayerSmall: function(mediaFileName, rtmpPathUrl, imagePathUrl, clientId) {
        var so = new SWFObject("/App_Themes/v2.0/swf/flvplayerSmall.swf", "flvplayer" + clientId, "320", "270", "9", "#FFFFFF");
        so.addParam("allowscriptaccess", "always");
        so.addParam("wmode", "opaque");
        so.addVariable("assetsPath", "/App_Themes/v2.0/swf/");
        so.addVariable("vidPath", mediaFileName);
        so.addVariable("rtmpPath", rtmpPathUrl);
        so.addVariable("imagePath", imagePathUrl);

        so.write(clientId);

        eval("window.flvplayer" + clientId + " = document.getElementById('flvplayer" + clientId + "')");
    },


    InsertVideoPlayerLargeWithXML: function(xmlFilePath, clientId, localeId) {

    var so = new SWFObject("/App_Themes/v2.0/swf/flvplayerLarge.swf", "flvplayer" + clientId, "428", "345", "9", "#FFFFFF");
        so.addVariable("assetsPath", "/App_Themes/v2.0/swf/VideoL2/English/");
        if (localeId == "2") {
            so = new SWFObject("/App_Themes/v2.0/swf/flvplayerLarge_china.swf", "flvplayer" + clientId, "428", "345", "9", "#FFFFFF");
            so.addVariable("assetsPath", "/App_Themes/v2.0/swf/VideoL2/China/");
        }
        so.addParam("wmode", "opaque");
        so.addParam("allowscriptaccess", "always");
        so.addVariable("xmlFileName", xmlFilePath);
        so.write(clientId);

        eval("window.flvplayer" + clientId + " = document.getElementById('flvplayer" + clientId + "')");
    },




    InsertVideoL2: function(xmlFileName, clientId, localeId, deepLinkID) {
        var so = new SWFObject("/App_Themes/v2.0/swf/L2VideoInteractive.swf", "L2VideoInteractive" + clientId, "916", "390", "9", "#FFFFFF");
        so.addParam("allowscriptaccess", "always");
        so.addVariable("assetsPath", "/App_Themes/v2.0/swf/VideoL2/English/");
        so.addParam("wmode", "opaque");
        if (localeId == "2") {
            so = new SWFObject("/App_Themes/v2.0/swf/L2VideoInteractive_china.swf", "L2VideoInteractive" + clientId, "916", "390", "9", "#FFFFFF");
            so.addVariable("assetsPath", "/App_Themes/v2.0/swf/VideoL2/China/");
            so.addParam("wmode", "opaque");
        }

        so.addVariable("xmlFileName", xmlFileName);
        so.addVariable("deepLinkID", deepLinkID);
        so.write(clientId);

        eval("window.L2VideoInteractive" + clientId + " = document.getElementById('L2VideoInteractive" + clientId + "')");
    },



    InsertInteractiveL2: function(xmlFileName, clientId, localeId) {
        var so = new SWFObject("/App_Themes/v2.0/swf/L2Interactive.swf", "L2Interactive" + clientId, "917", "386", "9", "#FFFFFF");
        so.addParam("wmode", "opaque");
        so.addParam("allowscriptaccess", "always");
        so.addVariable("assetsPath", "/App_Themes/v2.0/swf/InteractiveImages/");
        if (localeId == "2") {
            so = new SWFObject("/App_Themes/v2.0/swf/L2Interactive_china.swf", "Featuredflvplayer" + clientId, "917", "386", "9", "#FFFFFF");
            so.addVariable("assetsPath", "/App_Themes/v2.0/swf/InteractiveImages/China/");
            so.addParam("wmode", "opaque");
        }
        so.addVariable("xmlFileName", xmlFileName);

        so.write(clientId);

        eval("window.L2Interactive" + clientId + " = document.getElementById('L2Interactive" + clientId + "')");
    },


    OpenInteractivePopUp: function(InteractivePath, pheight, pWidth, clientId) {
        if (clientId == " ")//IE fails the window.open call if the clientId contains a space
            clientId = "";
        try {
            var x = window.open(InteractivePath, "interactive" + clientId, "status=0,toolbar=0,height=" + (pheight + 73) + ",width=" + pWidth);
        }
        catch (e) {
            alert(e);
        }
    },

    InsertFeaturedVideoPlayer: function(xmlFileName, moreVideosLink, clientId, localeId) {
        var so = new SWFObject("/App_Themes/v2.0/swf/Featuredflvplayer.swf", "Featuredflvplayer" + clientId, "448", "384", "9", "#FFFFFF");
        so.addParam("allowscriptaccess", "always");
        so.addVariable("assetsPath", "/App_Themes/v2.0/swf/VideoThumbPlayer/English/");
        so.addParam("wmode", "opaque");
        //for chinese size is 446x 400
        if (localeId == "2") {
            so = new SWFObject("/App_Themes/v2.0/swf/Featuredflvplayer_china.swf", "Featuredflvplayer" + clientId, "448", "405", "9", "#FFFFFF");
            so.addVariable("assetsPath", "/App_Themes/v2.0/swf/VideoThumbPlayer/China/");
            so.addParam("allowscriptaccess", "always");
            so.addParam("wmode", "opaque");
        }
        so.addVariable("xmlFileName", xmlFileName);
        so.addVariable("moreVideosLink", moreVideosLink);
        so.write(clientId);

        eval("window.Featuredflvplayer" + clientId + " = document.getElementById('Featuredflvplayer" + clientId + "')");
    },

    VideoStoryTip: function() {
        $$('.videoThumbColumn').each(function(ele) {
            var videoThumbs = ele.getElements('li');
            var videoLinks = ele.getElements('a');
            var videoTips = ele.getElements('.storyTip');

            videoTips.each(function(ele) {
                ele.addClass('hidden');
            });

            //videoLinks.setProperty('href','javascript:void(0)');
            videoThumbs.addEvents({
                'mouseover': function() {
                    this.getElements('.storyTip')[0].removeClass('hidden');
                },
                'mouseout': function() {
                    this.getElements('.storyTip')[0].addClass('hidden');
                }
            });
        });
    }
};


// -----------------------------------------------------------------------------------------------------

/*
Json.handleError = function( request ) { 
	str = "This is the generic Json.handleError() function. A generic XMLHttpRequest error has occured.\n";
	str += "[ERROR] The XMLHttpRequest has failed!\n";
	var myObj = fixD( Json.evaluate( request.responseText ) );
	for( var key in myObj ) {
		str += "[" + key + "] " + myObj[key] + "\n";
	}
	Site.ReportError( str );
};

Element.extend({
	findParent: function( className ) {
		var rollbackEle = this;
		while( rollbackEle != null && rollbackEle != document && ! rollbackEle.hasClass( className ) ) {
			rollbackEle = rollbackEle.getParent();
		};
		return rollbackEle;
	},
	selectIndexFromValue: function( val ) {
		if( this.selectedIndex != null ) {
			for( var i = 0; i < this.options.length; i++ ) {
				if( $(this).options[i].value == val || $(this).options[i].innerHTML == val ) {
					this.selectedIndex = i;
					return i;
				}
			}
		}
	},
	getElementsByTagAndAttribute: function( tagName, attributeName, attributeValue ) {
		if( window.webkit || window.ie ) {
			var skipArgumentValue = false;
			if( ! attributeValue ) {
				skipArgumentValue = true;
			}
			var allTags = this.getElements(tagName);
			var returnEle = [];
			allTags.each( function( ele ) {
				if( ele.getAttribute( attributeName ) ) {
					if( ( ele.getAttribute( attributeName ) == attributeValue ) || skipArgumentValue ) {
						returnEle.include( ele );
					}
				}
			});
			return returnEle ;
		} else {
			if( attributeValue ) {
				return this.getElements( tagName + '[' + attributeName + '="' + attributeValue + '"]');
			} else {
				return this.getElements( tagName + '[' + attributeName + ']');
			}
		}
	}
});
*/


var Site = {
	WebServices: {
		GetStatesZipByCountryId: '/webservice/Utility.asmx/GetStatesZipByCountryId',
		Log: '/webservice/Utility.asmx/Log',
		GetShippingCosts: '/webservice/Store.asmx/GetShippingCosts',
		GetValuesByFlag: '/webservice/Store.asmx/GetValuesByFlag',
		SetValuesByFlag: '/webservice/Store.asmx/SetValuesByFlag'
	},
	Init: function() { },
	// TODO: rename this to UpdateShippingCharges
	ShowShippingCosts: {
		Set: function( options ) {
			if( ! Site.ShowShippingCosts.__INIT ) {
				Site.ShowShippingCosts.__INIT = true;
				window.addEvent('domready', Site.ShowShippingCosts.Init );	
			};
			
			Site.ShowShippingCosts.__DROP_DOWN = options.DropDown;
			Site.ShowShippingCosts.__PRODUCT_LIST = options.ProductList;	
		},
		Init: function() {
			if( Site.ShowShippingCosts.__DROP_DOWN != null && Site.ShowShippingCosts.__PRODUCT_LIST ) {
			
				var dropDownEle = $(Site.ShowShippingCosts.__DROP_DOWN);
				var productListEle = $(Site.ShowShippingCosts.__PRODUCT_LIST);
				
				if( dropDownEle && productListEle ) {
				
					dropDownEle.addEvent( 'change', function() {
						var countryId = this.value;
						
						var UpdateShippingHandling = function( responseText ) {
							console.log( responseText );
							var myObj = JSON.decode( responseText ).d;
							
							productListEle.getElements('span.shippingCost').each(function(ele,index){
								ele.set('text', myObj[index] );
							});
						};
						
						var jsonPost = { CountryId: countryId };
						
						new Request({
							'url': Site.WebServices.GetShippingCosts,
							urlEncoded: false,
							'method': 'post',
							'headers': { 'Content-type': 'application/json' },
							'onFailure': JSON.handleError,
							'onComplete': UpdateShippingHandling
						}).send( JSON.encode( jsonPost ) );
					});
					
				};
			}
		}
	},
	PopupWindow: {
		Options: "status=0,toolbar=0,location=0,menubar=0,resizable=0,scrollbars=1,width=740,height=550",
		Target: "_MVHome_Popup",
		Add: function( id, options ) {
			if( ! options ) {
				options = Site.PopupWindow.Options;
			}
			if( ! Site.PopupWindow.__INIT ) {
				Site.PopupWindow.__ELEMENTS = [];
				window.addEvent('domready', Site.PopupWindow.Init );
				Site.PopupWindow.__INIT = true;
			}
			Site.PopupWindow.__ELEMENTS.push({ Id: id, Options: options });
		},
		Init: function() {
			Site.PopupWindow.__ELEMENTS.each(function( obj ){
				var ele = $(obj.Id);
				if( ele ) {
					ele.Options = obj.Options;
					ele.Url = ele.href;
					ele.addEvent('click', Site.PopupWindow.Show );
				}
			});
		},
		Show: function( e ) {
			var e = new Event(e);
			window.open( this.Url, Site.PopupWindow.Target, this.Options );			
			e.stopPropagation();			
			e.stop();
			return false;
		}
	},
	CountryStateSwitcher: {
		Add: function( options ) {
			if( ! Site.CountryStateSwitcher.__INIT ) {
				window.addEvent('domready', Site.CountryStateSwitcher.Init );
				Site.CountryStateSwitcher.__INIT = true;
				Site.CountryStateSwitcher.__ELEMENTS = [];
			}
			Site.CountryStateSwitcher.__ELEMENTS.push( options );
		},
		Init: function() {
			Site.CountryStateSwitcher.__ELEMENTS.each( function( options ) { 				
				var countryEle = $( options.CountryEle );
				countryEle.stateEle = $(options.StateEle );
				
				countryEle.addEvent('change', function() {
					var myAjax = new Ajax( Site.WebServices.GetStatesZipByCountryId, {
						'method': 'post',
						'headers': { 'Content-type': 'application/json' },
						'onFailure': Json.handleError,
						'onComplete': Site.CountryStateSwitcher.UpdateStateEle.bind( this )
					});

					var jsonPost = { CountryId: this.value };

					myAjax.request( Json.toString( jsonPost ) );
				});
			
			});
		},
		/*
		 * is a call back function where 'this.stateEle' is the parent DOM element where its 2 children are a select box and input box
		 * this function will check responseObj.States, if its an array, it'll use the select, if its null, it'll show the input
		 */
		UpdateStateEle: function( responseText ) {	
			var responseObj = null;
			
			if( $type(responseText) == "string" ) {
				responseObj = fixD( Json.evaluate( responseText ) );
			} else { 
				responseObj = responseText;
			}
			
			var parentEle = this.stateEle.getParent();
			var stateDD = this.stateEle.getElement('select');
			stateDD.empty();
			
			if( responseObj.States ) {				
				if( responseObj.StateLabel ) {
					stateDD.adopt(
						new Element( 'option', {
							'value': 0
						}).setText( "-- Select  " + responseObj.StateLabel + " --" )
					);
				} else {
					stateDD.adopt(
						new Element( 'option', {
							'value': 0
						}).setText( "-- Select State --" )
					);
				}
				responseObj.States.each( function( ele ) {
					if( ele.StateName ) {
						stateDD.adopt( 
							new Element( 'option', { 
								'value': ele.StateCode
							}).setText( ele.StateName )
						);
					}
				});
				
				this.stateEle.getElement('input').addClass('hidden');
				this.stateEle.getElement('select').removeClass('hidden');
				parentEle.getElement('.stateLabel').removeClass('notRequiredField');
				parentEle.getElement('.zipCodeLabel').removeClass('notRequiredField');
			} else {
				this.stateEle.getElement('input').removeClass('hidden');
				this.stateEle.getElement('input').value = "";
				this.stateEle.getElement('select').addClass('hidden');
				parentEle.getElement('.stateLabel').addClass('notRequiredField');
				parentEle.getElement('.zipCodeLabel').addClass('notRequiredField');
			}
			
			if( responseObj.StateLabel ) {
				parentEle.getElement('.stateLabel').setHTML( responseObj.StateLabel + '<em class="errorMessage">*</em>' );
			}
			
			var zipEle = parentEle.getElement('div.zipCode input');
			if( zipEle ) {
				zipEle.value = "";
			}
		}
	},
	ReportError: function( message ) {
		var myAjax = new Ajax( Site.WebServices.Log, {
			'method': 'post',
			'headers': { 'Content-type': 'application/json' }
		});
		
		var jsonPost = {
			'title': 'JavaScript Error',
			'message': message
		};
		
		if( console ) {
			console.log( "[NOTE] Bypassing Event Logger" );
			console.log( jsonPost.title );
			var MessageLine = jsonPost.message.split("\n");
			MessageLine.each( function( item ) {
				console.log( item );
			});
		} else { 
			myAjax.request( Json.toString( jsonPost ) );
		}
	}
};

var McK = { 
	NewsletterPicker: {
		Set: function( options ) {
			McK.NewsletterPicker.__CHECKBOX = options.CheckboxId;
			if( ! McK.NewsletterPicker.__INIT ) {
				window.addEvent('domready', McK.NewsletterPicker.Init );
			}
		},	
		Init: function() {
			var mainEle = $(McK.NewsletterPicker.__CHECKBOX);
			if( mainEle ) {
				var otherRadios = mainEle.findParent('monthlyNewsletter').getElements('.emailType input');
				
				otherRadios.each( function( ele ) {
					ele.disabled = ! mainEle.checked;
				});
				
				mainEle.addEvent('click', function() {
					var found = false;
					otherRadios.each( function( ele, index ) { 
						ele.disabled = ! mainEle.checked;
						if( ele.checked ) {
							found = true;
						}
						
					});
					if( ! found ) {
						otherRadios[0].checked = true;
					}
				});
			};
		}	
	}
};

window.addEvent('domready', Site.Init );
