var AppBehavior = Class.create();
AppBehavior.Load = function() {
    if (typeof (Application) == 'undefined') { setTimeout(AppBehavior.Load, 50); return; }
    OS.RegisterBehaviour(AppBehavior.Rules);
}
AppBehavior.Rules = {
    '#Cnt_Content': function(element) {
        Event.observe(window, 'resize', _OnResize);
    },
    '.command': function(element) {
        Application.SetRollover(element);
    },
    '.viewSplash #Cnt_SplashMedia': function() {
        swfobject.embedSWF('flash/home.swf', 'Cnt_SplashMedia', 1010, 475, '8', 'flash/expressInstall.swf', {}, { wmode: 'transparent' }, null);
    },
    '.viewGiveaway #Cnt_Media': function() {
        Element.show('Cnt_Media');
        swfobject.embedSWF('flash/giveaway.swf', 'Cnt_Media', 922, 555, '8', 'flash/expressInstall.swf', {}, { wmode: 'transparent' }, null);
    },
    '#Cnt_Content a': function(element) {
        Application.SetRollover(element);
    },
    '.togglable': function(element) {
        Application.SetTogglableBehavior(element, null, _OnResize);
    },
    'a': function(element) {
        Event.observe(element, 'click', function() {
            AppBehavior.StopVideos();
        });
    },
    '#Nav_Main .navItem': function(element) {
        Application.SetRollover(element);
        Event.observe(element, 'click', function() {
            //AppBehavior.StopVideos();
            var eHref = Element.down(element, 'a');
            if (eHref) top.location.href = eHref.href;
        });
    },
    '#Nav_Contact .navItem': function(element) {
        Application.SetRollover(element);
    },
    '#Nav_Footer .navItem': function(element) {
        Application.SetRollover(element);
    },
    '#Pv_CalloutSpotlights': function(element) {
        Application.SetPanelViewBehavior(element, _OnResize);
        if (!$('Dv_SpotlightList')) Application.RotatePanelView(element, 9000);
    },
    'body': function(element) {
        if (Prototype.Browser.IE) Element.addClassName('Body', 'ie' + Prototype.BrowserVersion());

        Event.observe($(document), 'click', function(e) {
            $$('.autocomplete').each(function(autocomplete) {
                if (Position.within(autocomplete, e.pointerX(), e.pointerY())) return;
                Element.hide(autocomplete);
            });
            var eDp = $('Dp_Calendar');
            if (eDp) {
                if (Position.within(eDp, e.pointerX(), e.pointerY())) return;
                if (AppBehavior.DatePicker) AppBehavior.DatePicker.hide();
                //_OnResize();
            }
        });
        if (typeof (DatePickerModel) != 'undefined') {
            AppBehavior.DatePicker = new DatePickerModel('Dp_Calendar', {
                onDateSelected: AppBehavior.OnDateSelected
            });
        }
        Application.CurrentHash = null;
        Application.InitHistory();

        window.onbeforeunload = function() {
            AppBehavior.StopVideos();
        }
    },
    '.cmdPrint': function(element) {
        Event.observe(element, 'click', function() { if (window.print) window.print(); });
    },
    '.datetime': function(element) {
        var eCommand = Element.down(element, '.cmdGetDate');
        var eInput = Element.down(element, 'input');
        if (!eInput || !eCommand) { console.warn(' no date on element: ' + element.identify()); return; }
        Event.observe(eCommand, 'click', function() {
            if (AppBehavior.DatePicker.isVisible) return;
            AppBehavior.FireGetDate(eInput, eCommand);
        });
    },
    '#Dv_SignIn .textbox input': function(element) {
        Event.observe(element, 'keydown', function(e) {
            if (e.keyCode == 13) {
                Application.Track('View-SignInAttempted');
                __doPostBack('ctl00$Cph_Content$PersonalizationSignIn$BtnSignIn', '');
            }
        });
    },
    '#Dv_Register .cmdRegister': function(element) {
        Event.observe(element, 'mousedown', function(e) {
            if (!AppBehavior.ValidRegisterForm()) return;
            Application.Track('View-RegisterAttempted');
            __doPostBack('ctl00$Cph_Content$PersonalizationRegister$BtnRegister', '');
        });
    },
    '#Dv_SignIn .cmdSignIn': function(element) {
        Event.observe(element, 'mousedown', function(e) {
            if (!AppBehavior.ValidSignInForm()) return;
            Application.Track('View-SignInAttempted');
            __doPostBack('ctl00$Cph_Content$PersonalizationSignIn$BtnSignIn', '');
        });
    },
    '#fProfileCreated': function(element) {
        Application.Track('View-ProfileCreated');
    },
    '#Cmd_ForgotPassword': function(element) {
        Event.observe(element, 'click', function() {
            Application.SwitchPanel('Cnt_SignIn', 'Pnl_Forgot');
            _OnResize();
        });
    },
    '#Cmd_SendPassword': function(element) {
        Event.observe(element, 'click', function() {
            __doPostBack('ctl00$Cph_Content$PersonalizationSignIn$BtnSendPassword', '');
        });
    },
    '#Cnt_SignIn .cmdCancel': function(element) {
        Event.observe(element, 'click', function() {
            AppBehavior.ResetValidation();
            Application.SwitchPanel('Cnt_SignIn', 'Pnl_SignIn');
            _OnResize();
        });
    },
    '#Cnt_Register .data input': function(element) {
        Event.observe(element, 'blur', function() {
            AppBehavior.ValidRegisterForm(element);
        });
        Event.observe(element, 'focus', function() {
            if (element.value.length <= 0) return;
            AppBehavior.ValidRegisterForm(element);
        });
        Event.observe(element, 'click', function() {
            if (element.value.length <= 0) return;
            AppBehavior.ValidRegisterForm(element);
        });
    },
    '#Cnt_Register .data select': function(element) {
        Event.observe(element, 'change', function() {
            AppBehavior.ValidRegisterForm(element);
        });
    },
    '#Cnt_SignIn .data input': function(element) {
        Event.observe(element, 'blur', function() {
            AppBehavior.ValidSignInForm(element);
        });
        Event.observe(element, 'focus', function() {
            if (element.value.length <= 0) return;
            AppBehavior.ValidSignInForm(element);
        });
        Event.observe(element, 'click', function() {
            if (element.value.length <= 0) return;
            AppBehavior.ValidSignInForm(element);
        });
    },
    '#Cnt_SignIn .data select': function(element) {
        Event.observe(element, 'change', function() {
            AppBehavior.ValidSignInForm(element);
        });
    }
};
AppBehavior.DatePicker = null;
AppBehavior.CurrentDateElement = null;
AppBehavior.OnDateSelected = function(element, square) {
    if (AppBehavior.CurrentDateElement) {
        AppBehavior.CurrentDateElement.value = square.Date;
        AppBehavior.CurrentDateElement.focus();
        AppBehavior.CurrentDateElement.blur();
    }
    AppBehavior.DatePicker.hide();
    _OnResize();
}
AppBehavior.FireGetDate = function(input, command) {
    AppBehavior.CurrentDateElement = input;
    AppBehavior.CurrentDateElement.focus();
    AppBehavior.DatePicker.show();
    var offsets = Element.cumulativeOffset(command);
    var iTop = offsets[1];
    var iLeft = offsets[0];
    Element.setStyle('Dp_Calendar', { left: iLeft + 'px', top: iTop + 'px' });
    AppBehavior.DatePicker.show();
    var sDate = AppBehavior.CurrentDateElement.value || null;
    AppBehavior.DatePicker.selectDate(new Date(sDate));
    _OnResize();
}
AppBehavior.NavigateTo = function(section) {
    if (Element.hasClassName('Body', 'viewSuccessStories')) {
        StoryBehavior.SwitchSection(section);
    } else if (Element.hasClassName('Body', 'viewNews')) {
        NewsBehavior.SwitchSection(section);
    } else if (Element.hasClassName('Body', 'viewResources')) {
        ResourceBehavior.SwitchSection(section);
    }
}
AppBehavior.OnChangeHistory = function(hash) {
    if (hash.length == 0 && Application.CurrentHash) {
        Application.CurrentHash = null;
    }
    if (Application.CurrentHash != hash) {
        Application.CurrentHash = hash;
        AppBehavior.NavigateTo(hash);
    }
    if (Prototype.Browser.IE) setTimeout(function() { Application.SetTitle(Application.CurrentTitle); }, 0);
}

AppBehavior.ShowAutocompleter = function(autocompleter) {

    autocompleter.changed = true;
    autocompleter.hasFocus = true;
    if (autocompleter.observer) clearTimeout(autocompleter.observer);
    autocompleter.observer =
		setTimeout(autocompleter.onObserverEvent.bind(autocompleter), autocompleter.options.frequency * 1000);
}
AppBehavior.Freeze = function(key, options) {
    if (key == 'Admin') return AppBehavior.Freeze('All', { zIndex: 1 });
    if (!options) options = {};
    options = Object.extend({
        zIndex: 50,
        opacity: .5,
        backgroundColor: '#472E21'
    }, options);
    var sId = 'Frozen_' + key;
    var eFrozen = $(sId);
    var eBody = document.getElementsByTagName('body')[0];
    if (!eFrozen) {
        eFrozen = document.createElement('div');
        eFrozen.id = sId;
        Element.hide(eFrozen);
        eBody.appendChild(eFrozen);
    }

    Element.addClassName(eFrozen, 'frozen');
    var iTop = 0;
    if (key == 'Admin') iTop = -100;
    Element.setStyle(eFrozen, {
        position: 'absolute',
        top: iTop + 'px', left: 0,
        overflow: 'hidden',
        backgroundColor: options.backgroundColor,
        zIndex: options.zIndex
    });
    Element.setOpacity(eFrozen, options.opacity);
    //forced
    var pageWidth = Element.getWidth(eBody);
    var pageHeight = Element.getHeight(eBody);
    if (key == 'Admin') pageWidth = 1040;
    Element.setStyle(eFrozen, {
        width: pageWidth + 'px',
        height: (pageHeight + 600) + 'px'
    });

    Element.show(eFrozen);
    if (key == 'All') Element.setStyle('Body', { overflow: 'hidden' });
}
AppBehavior.Unfreeze = function(key) {
    if (key == 'Admin') AppBehavior.Unfreeze('All');
    var sId = 'Frozen_' + key;
    var eFrozen = $(sId);
    if(eFrozen) Element.hide(eFrozen);
    if (key == 'All') Element.setStyle('Body', { overflow: '' });
}
AppBehavior.StopVideos = function() {
    var oPlayer = Application.GetFlashObject('Media_Canvas');
    if (oPlayer && oPlayer.stopVideo) oPlayer.stopVideo();
}
AppBehavior.OnFlashLoaded = function(key) {
    if (key == 'LifestylePlayer') {
        var oPlayer = Application.GetFlashObject('Media_Canvas');
        if(!oPlayer) return;
        if(Element.hasClassName('Body', 'viewSporting')) {
            oPlayer.playVideo('sportingAmenities/sporting-amenities');        
        } else if(Element.hasClassName('Body', 'viewFamily'))  {
            oPlayer.playVideo('familyActivities/family-activities');        
        } else {
            oPlayer.playVideo('lifestyle');        
        }
    }
}
AppBehavior.FireResize = function() {
    Element.show('Ftr_UI');
    Element.show('Ftr_Main');
    Element.show('Mod_Callouts');
    if ($('Dv_SpotlightList')) return;
    var eCnt = $('Cnt_Content');
    var eFtr = $('Ftr_UI');
    var iWidth = Element.getWidth('App_Main') + 25;
    Element.setStyle(eCnt, { height: 'auto' });
    Element.setStyle(eFtr, { width: 'auto' });
    if (Element.getWidth(eFtr) < iWidth) Element.setStyle(eFtr, { width: iWidth + 'px' });
    Element.setStyle(eCnt, { height: 'auto' });
    var offsetsFtr = eFtr.cumulativeOffset();
    var offsetsCnt = eCnt.cumulativeOffset();
    var topFtr = offsetsFtr[1];

    if (_Resized <= 1) {
        Element.hide('Ftr_UI');
        Element.hide('Ftr_Main');
        Element.hide('Mod_Callouts');
    }
    var iFtrHeight = parseInt(Element.getStyle(eFtr, 'height')) || 0;
    var iMinHeight = 500;  //370; Must be greater than horizon
    if (Element.hasClassName('Body', 'viewSplash')) iMinHeight = 500;
    var iAdditional = 33; //Spotlight - Footer (69-36)
    var topCnt = offsetsCnt[1];
    var iHeight = Math.max(iMinHeight, topFtr - topCnt - iFtrHeight - iAdditional);
    Element.setStyle(eCnt, { height: iHeight + 'px' });
    if (_Resized == 1) {
        if (!(Prototype.Browser.IE && Prototype.BrowserVersion() <= 6)) {
            var ef1 = new Effect.Appear('Ftr_UI', { queue: { position: 'end', scope: 'footer' }, duration: .2 });
            var ef2 = new Effect.Appear('Ftr_Main', { queue: { position: 'end', scope: 'footer' }, duration: .5 });
            var ef3 = new Effect.Appear('Mod_Callouts', { queue: { position: 'end', scope: 'callouts' }, duration: 1.0 });
            ef1 = null; ef2 = null; ef3 = null;
        } else {
            Element.show('Ftr_UI');
            Element.show('Ftr_Main');
            Element.show('Mod_Callouts');
        }
    }
    _Resized++;
}
AppBehavior.ResetValidation = function() {
    var eForm = $('aspnetForm');
    Application.ThrowMessages = new Hash();
    Application.ResetThrowStatus($('Hud_ValidateRegister'), eForm);
    Application.ResetThrowStatus($('Hud_ValidateSignIn'), eForm);    
}
AppBehavior.ValidRegisterForm = function(triggerInput) {
    var eHud = $('Hud_ValidateRegister');
    var eForm = $('aspnetForm');
    if (triggerInput) {
        var eParent = triggerInput.parentNode;
        var eParentParent = eParent.parentNode;
        if (Element.hasClassName(eParentParent, 'radioList')) {
            Element.removeClassName(eParentParent, 'highlight');
        } else if (Element.hasClassName(eParent, 'checkbox')) {
            Element.removeClassName(eParent, 'highlight');
        } else {
            Element.removeClassName(triggerInput, 'highlight');
        }
    } else { AppBehavior.ResetValidation(); }

    Application.RequireTextbox(eHud, 'fRegFirstName', 'First Name required', triggerInput);
    Application.RequireTextbox(eHud, 'fRegLastName', 'Last Name required', triggerInput);
    Application.RequireTextbox(eHud, 'fRegEmail', 'Email required', triggerInput);
    Application.RequireTextboxMask(eHud, 'fRegEmail', Application.ValidateEmail, 'Email Address is not a valid email address', triggerInput);
    Application.RequireEqual(eHud, 'fRegEmail', 'fRegEmailConfirm', 'Email addresses do not match', triggerInput);
    Application.RequireTextbox(eHud, 'fRegPassword', 'Password required', triggerInput);
    Application.RequireTextbox(eHud, 'fRegPasswordConfirm', 'Confirmation Password required', triggerInput);
    Application.RequireEqual(eHud, 'fRegPassword', 'fRegPasswordConfirm', 'Passwords do not match', triggerInput);

    var bHasStatus = Application.ThrowStatusSummary(eHud);
    var bValidThrow = Application.IsValidThrowStatus(eHud);
    //if (triggerInput) Element[(bHasStatus) ? 'show' : 'hide'](eHud);
    _OnResize();
    setTimeout(_OnResize, 50);
    setTimeout(_OnResize, 500);
    return bValidThrow;
}

AppBehavior.ValidSignInForm = function(triggerInput) {
    var eHud = $('Hud_ValidateSignIn');
    var eForm = $('aspnetForm');
    if (triggerInput) {
        var eParent = triggerInput.parentNode;
        var eParentParent = eParent.parentNode;
        if (Element.hasClassName(eParentParent, 'radioList')) {
            Element.removeClassName(eParentParent, 'highlight');
        } else if (Element.hasClassName(eParent, 'checkbox')) {
            Element.removeClassName(eParent, 'highlight');
        } else {
            Element.removeClassName(triggerInput, 'highlight');
        }
    } else { AppBehavior.ResetValidation(); }

    Application.RequireTextbox(eHud, 'fUsername', 'Email Address required', triggerInput);
    Application.RequireTextbox(eHud, 'fPassword', 'Password required', triggerInput);

    var bHasStatus = Application.ThrowStatusSummary(eHud);
    var bValidThrow = Application.IsValidThrowStatus(eHud);
    //if (triggerInput) Element[(bHasStatus) ? 'show' : 'hide'](eHud);
    _OnResize();
    setTimeout(_OnResize, 50);
    setTimeout(_OnResize, 500);
    return bValidThrow;
}

AppBehavior.Load();

