﻿/* 
* TacoBell.com sitewide code.
* Global page initialization code is at the bottom.
*/

if (typeof tacoBell === 'undefined') { tacoBell = {}; }
if (!tacoBell.isIE) { tacoBell.isIE = false; }
if (!tacoBell.isIE6) { tacoBell.isIE6 = false; }
if (!tacoBell.isPrintable) { tacoBell.isPrintable = false; }

if (!tacoBell.dayParts) {
    tacoBell.dayParts = {
		schedule: [
			'latenight', // 12am
			'latenight', // 1am
			'latenight', // 2am
			'latenight', // 3am
			'morning', // 4am
			'morning', // 5am
			'morning', // 6am
			'morning', // 7am
			'morning', // 8am
			'morning', // 9am
			'morning', // 10am
			'midday', // 11am
			'midday', // 12pm
			'midday', // 1pm
			'midday', // 2pm
			'afternoon', // 3pm
			'afternoon', // 4pm
			'evening', // 5pm
			'evening', // 6pm
			'evening', // 7pm
			'evening', // 8pm
			'latenight', // 9pm
			'latenight', // 10pm
			'latenight' // 11pm
		],
		getPartForHour: function()
		{
			return this.schedule[new Date().getHours()];
		}
	};
}

if (!tacoBell.constants) {
	tacoBell.constants = {
		REQUIRED_FLASH_PLAYER_VERSION: '9.0.115',
		EXPRESS_INSTALL_PATH: 'shared/express_install.swf',
		corpusGothicSrc: '/swf/shared/corpusgothic.swf' 
	};
}

if (!tacoBell.utils) { tacoBell.utils = {}; }

if (!tacoBell.utils.RolloverManager) {
    tacoBell.utils.RolloverManager = (function() {
        var _roEls;
        function _setUp() {
            _getRolloverElements();
            _setUpRollovers();
        }
        function _getRolloverElements() {
            _roEls = $('.rollover');
        }
        function _setUpRollovers() {
            var _roType, _roImages;
            _roEls.each(function() {
                var _imgSelfRO = $(this);
                _roType = _imgSelfRO.get(0).tagName;
                _addOverListener(_imgSelfRO, _imgSelfRO, _roType);
            });
        }
        function _setUpModalRollovers(modalID) {
            var _roElsModal = $('#' + modalID + ' .rollover');
            var _roType, _roImages;
            _roElsModal.each(function() {
                _roType = $(this).get(0).tagName;
                _addOverListener($(this), $(this), _roType);
            });
        }
        function _addOverListener(listenObj, rolloverObj, roType) {
            roType = roType.toLowerCase();
            if (roType == 'img') {
                _createImgRollover(listenObj, rolloverObj);
            }
        }
        function _createImgRollover(listenObj, rolloverObj) {
            var imgOverName = (tacoBell.isIE6) ? rolloverObj.attr('oSrc').replace(/_off/gi, '_over') : rolloverObj.attr('src').replace(/_off/gi, '_over');
            var imgOver = new Image();
            imgOver.src = imgOverName;
            listenObj.hover(
				function() {
                    var swapThisOver = rolloverObj.get(0);
                    swapThisOver.src = imgOver.src;
				    if (tacoBell.isIE6) {
				        IEPNGFix.process(swapThisOver, 0);
				    }
				},
				function() {
    				var swapThisOff = rolloverObj.get(0);
    				swapThisOff.src = (tacoBell.isIE6) ? rolloverObj.attr('oSrc').replace(/_over/gi, '_off') : swapThisOff.src.replace(/_over/gi, '_off');
				    if (tacoBell.isIE6) {
				        IEPNGFix.process(swapThisOff, 0);
				    }
				}
			);
        }
        return {
            setUp: function() {
                _setUp();
            },
            setUpModalRollovers: function(modalID) {
                _setUpModalRollovers(modalID);
            },
            createImgRollover: function(listenObj, rolloverObj) {
                _createImgRollover(listenObj, rolloverObj);
            }
        };
    })();
}

/*
* Utility method to create modal dialogs.
* @requires jquery.simplemodal-1.3.3.js
* @requires jScrollPane-1.2.3.min.js
*/
if (!tacoBell.utils.ModalDialogManager) {
    tacoBell.utils.ModalDialogManager = (function(containerID, contentID) {
        var _modalContentDivs, _modalDialogClass;
        var _modalDialogsLoaded = false;
        function _setUp() {
            if (!tacoBell.isPrintable) {
                _modalContentDivs = $('.modalContent');
                _modalDialogClass = 'modalDialog';
                _createModalDialogs();
            } else {
                $('.modalContent').hide();
            }
        }
        function _createModalDialogs() {
            if (_modalContentDivs.length) {
                _modalContentDivs.each(function() {
                    _moveModalContent($(this));
                });
            }
            _modalDialogsLoaded = true;
        }
        function _moveModalContent(obj) {
            var thisModalId = obj.attr('id') + 'Modal';
            var that = obj;
            $('body').append('<div id="' + thisModalId + '" class="' + _modalDialogClass + '"></div>');
            $('#' + thisModalId).load('/includes/modal_dialog_template.html', function() {
                $(this).find('.content').append(that.html());
                that.remove();
                // trigger custom event for availability of login modal
                // to be used for immediately opening login modal on page load
                if (thisModalId == 'logInModal') {
                    $(window).trigger('logInModalLoaded');
                }
            });
        }
        function _openModal(modalContentID, options) {
            var theseOptions = $.extend({
                overlayClose: true,
                onShow: function(dialog) {
                    if (tacoBell.isIE6) {
                        dialog.data.find('.left_upper_corner,.right_upper_corner,.left_lower_corner,.right_lower_corner').addClass('transparent');
                    }
                    $(window).trigger('mdm:shown');
                }
            }, options || {});
            var thisModalID = modalContentID + 'Modal';
            $('#' + thisModalID).modal({
                opacity: 60,
                overlayClose: theseOptions.overlayClose,
                onShow: theseOptions.onShow,
                onOpen: function(dialog) {
                    dialog.overlay.show();
                    dialog.container.show();
                    dialog.data.show();
                    $(window).trigger('mdm:opened');
                },
                onClose: function(dialog) {
                    dialog.data.hide();
                    dialog.container.hide();
                    dialog.overlay.hide();
                    $.modal.close();
                    $(window).trigger('mdm:closed');
                }
            });
            $('#' + thisModalID).parent().parent().addClass(modalContentID + 'ModalContainer');
            // if modal dialog contains element w/class "modalScrollable", init jScrollPane on it
            if ($('#' + thisModalID + ' .modalScrollable').length) {
                // Lazy load jScrollPane
                $.lazy({
                    src: '/js/libraries/jScrollPane-1.2.3.min.js',
                    name: 'jScrollPane',
                    cache: true
                });
                $.lazy({
                    src: '/js/libraries/jquery.mousewheel.min.js',
                    name: 'mousewheel',
                    cache: true
                });
                $('#' + thisModalID + ' .modalScrollable').jScrollPane({
                    animateTo: true,
                    animateInterval: 100,
                    animateStep: 1,
                    scrollbarWidth: 9
                });
            }
            // if modal dialog contains elements w/class "rollover", init rollover manager on it
            if ($('#' + thisModalID + ' .rollover').length) {
                tacoBell.utils.RolloverManager.setUpModalRollovers(thisModalID);
            }
            // if modal dialog continues a print button, hook it up
            var thisModalPrint = $('#' + thisModalID + ' .modalPrint');
            if (thisModalPrint.length) {
                thisModalPrint.eq(0).bind('click', function() {
                    tacoBell.utils.PrintManager.openModalPrintWin(thisModalID);
                });
            }
        }
        return {
            setUp: function() {
                _setUp();
            },
            openModal: function(modalContentID, options) {
                _openModal(modalContentID, options);
            },
            modalDialogsLoaded: function() {
                return _modalDialogsLoaded;
            }
        };
    })();
}

/*
* Stripe odd columns of a table using a classname.
* options {
*	tableID: [String id],
*	oddColumnClass: [String class]
* }
*/
if (!tacoBell.utils.stripeColumns) {
    tacoBell.utils.stripeColumns = function(options) {
        if (typeof options.oddColumnClass == 'undefined') {
            options.oddColumnClass = 'odd';
        } else {
            options.oddColumnClass = options.oddColumnClass;
        }
        $('#' + options.tableID + ' tr').each(function() {
            $(this).children().filter(':odd').addClass(options.oddColumnClass);
        });
        //if (!tacoBell.isPrintable) {
        //} else {
        //jQueryObj.each(function() {
        //$(this).children().filter(':odd').addClass('nutStatColHLPrint');
        //});
        //}
    };
}

/*
* Case-insensitive version of jQuery's native "contains" selector
* http://stackoverflow.com/questions/187537/is-there-a-case-insensitive-jquery-contains-selector
* http://stackoverflow.com/questions/1407434/is-there-anyway-to-speed-up-this-solution-for-a-case-insensitive-jquery-contains
*/
$.extend(
	$.expr[':'].containsCI = function(a, i, m) {
		return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
	}
);

/*
* Manage list with expandable and collapsible list items with arrow icons.
* @param {Object} options An object containing options properties: listItemHeaderclass, collapsedArrowClass, expandedArrowClass 
* @requires tacoBell.utils.RolloverManager
*/
if (!tacoBell.utils.expandableList) {
    tacoBell.utils.expandableList = function(options) {
        // check for passed options obj and set defaults
        options = (typeof options == 'undefined') ? {} : options;
        options.listItemHeaderClass = (typeof options.listItemHeaderClass == 'undefined') ? 'expandItem' : options.listItemHeaderClass;
        options.collapsedArrowClass = (typeof options.collapsedArrowClass == 'undefined') ? 'arrowCollapsed' : options.collapsedArrowClass;
        options.expandedArrowClass = (typeof options.expandedArrowClass == 'undefined') ? 'arrowExpanded' : options.expandedArrowClass;
        // list item text image over state when arrow rolled over
        var collapsedArrows = $('.' + options.collapsedArrowClass);
        collapsedArrows.each(function() {
            tacoBell.utils.RolloverManager.createImgRollover($(this), $(this).next());
        });
        var listItemHeaders = $('.' + options.listItemHeaderClass + ' > *');
        listItemHeaders.click(function() {
            var arrow = (this.tagName.toLowerCase() == 'div') ? this : $(this).prev().get(0);
            $(arrow).toggleClass(options.expandedArrowClass);
            $(this).parent().next().toggle();
            if (!tacoBell.isIE6) {
                var fs = $('#footerShadow');
                var fsPosTop = $('#content').height() - fs.height();
                fs.css({
                    'bottom': 'auto',
                    'top': fsPosTop
                });
            }
        });
    };
}

/*
* Readjust height of content area when it changes dynamically --
* IE doesn't always reposition the footer shadow correctly.
*/
if (!tacoBell.utils.adjustContentHeight) {
    tacoBell.utils.adjustContentHeight = function() {
        var maxHeight = 0;
        $('#content .inner > div, #content .inner > form, #footer').each(function() {
            var tmpHeight = $(this).height() + $(this).position().top;
            if (tmpHeight > maxHeight) {
                maxHeight = tmpHeight;
                $('#content').height(maxHeight);
            }
        });
    };
}

/*
* Manager for share modal dialog.
*/
if (!tacoBell.utils.ShareManager) {
    tacoBell.utils.ShareManager = (function(options) {
        var _thisUrl, _thisText;
        function _setUp() {
            _thisUrl = window.location.href;
            //_thisText = $.trim(document.title);
            _thisText = 'Check out the new TacoBell.com';
            $('#share').bind('click', _openShareDialog);
        }
        function _openShareDialog() {
            tacoBell.utils.ModalDialogManager.openModal('dialogShare');
            _updateLinks();
            $('#shareTabs').tabs({
                tabsselect: function(e, data) {
                    var tabLink = $(data.tab);
                    var tab_name;
                    switch (tabLink.attr('href')) {
                        case '#tabFb':
                            tab_name = 'facebook';
                            break;
                        case '#tabMs':
                            tab_name = 'myspace';
                            break;
                        case '#tabTw':
                            tab_name = 'twitter';
                            break;
                    }
                    Tracker.trackClick('share>web>' + tab_name, 'share', {
                        prop5: tab_name + ': ' + sharing_id
                    }, null, t);
                    if (tacoBell.isIE6) {
                        $('#shareTabs li, #shareTabs a').addClass('transparent');
                    }
                }
            });
            var sharing_id = window.location.pathname.replace(/^\/|\/$/g, '').replace(/\/|\-/g, '_').toLowerCase();
            var t = Tracker.newTracker();

            Tracker.trackPage('share', 'share', null, null, t);
            $('#btnPostItFb').click(function() {
                Tracker.trackClick('share>web>facebook>post_it', 'share', {
                    prop5: 'facebook post_it: ' + sharing_id
                }, null, t);
            });

            $('#btnPostItMs').click(function() {
                Tracker.trackClick('share>web>myspace>post_it', 'share', {
                    prop5: 'myspace post_it: ' + sharing_id
                }, null, t);
            });

            $('#btnPostItTw').click(function() {
                Tracker.trackClick('share>web>twitter>post_it', 'share', {
                    prop5: 'twitter post_it: ' + sharing_id
                }, null, t);
            });
        }
        function _updateLinks() {
            $('#btnPostItFb').attr('href', $.param.querystring($('#btnPostItFb').attr('href'), {
                't': _thisText,
                'u': _thisUrl
            }));
            $('#btnPostItMs').attr('href', $.param.querystring($('#btnPostItMs').attr('href'), {
                't': _thisText,
                'u': _thisUrl
            }));
            $('#btnPostItTw').attr('href', $.param.querystring($('#btnPostItTw').attr('href'), {
                'status': _thisText + ' ' + _thisUrl
            }));
        }
        return {
            setUp: function() {
                _setUp();
            },
            openShareDialog: function() {
                _openShareDialog();
            }
        };
    })();
}

/*
* Manages setting up print button event handler for nonprintable pages
* and initialization of printable pages and modal dialogs.
*/
if (!tacoBell.utils.PrintManager) {
    tacoBell.utils.PrintManager = (function() {
        var thisURL = $.deparam.querystring();
        if ((typeof thisURL.print != 'undefined') && (thisURL.print)) {
            tacoBell.isPrintable = true;
        }
        /*
        * Set up the printable version of a page or modal.
        */
        function _setUpPrintable() {
            _setActiveStylesheet('print_preview');
            _removeLinks();
            _artTextToAltText();
            _artTextToPrintArtText();
            window.print();
        }
        function _setActiveStylesheet(title) {
            var i, a, main;
            for (i = 0; (a = document.getElementsByTagName('link')[i]); i++) {
                if (a.getAttribute('rel').indexOf('style') != -1 && a.getAttribute('title')) {
                    a.disabled = true;
                    if (a.getAttribute('title') == title) {
                        a.disabled = false;
                    }
                }
            }
        }
        /*
        * Remove all links, retaining only their inner contents.
        */
        function _removeLinks() {
            // remove links
            $('a').each(function() {
                var text = $(this).text();
                // from text
                if (text.length) {
                    $(this).replaceWith(text);
                    // from images and other
                } else {
                    $(this).replaceWith($(this).children().eq(0));
                }
            });
        }
        /*
        * Replace white arttext images with class "printAlt" with their alt attributes.
        */
        function _artTextToAltText() {
            $('.printAlt').each(function() {
                var altAttr = $(this).attr('alt');
                $(this).replaceWith(altAttr);
            });
        }
        /*
        * Replace white arttext images with class "printImg" with printable black versions.
        * Also replace Flash logo w/printable JPG version of logo.
        */
        function _artTextToPrintArtText() {
            $('.printImg').each(function() {
                $(this).attr('src', $(this).attr('src').replace(/\.png/gi, '_print.png'));
            });
            $('#headerLogoFlash').remove();
            $('#headerLogo').css({padding: '0'}).append('<img src="' + site_home + 'images/logo_tb_print.jpg" alt="Taco Bell" width="114" height="52">');
        }
        /*
        * Add click event handler to print button, w/special code for policies page(s).
        */
        function _setUpPrintBtn() {
            if ($('#print').length) {
                // remove hash from URL if present
                var regExpr = new RegExp('#' + $.param.fragment());
                var printUrl = window.location.href.replace(regExpr, '');
                printUrl = $.param.querystring(printUrl, 'print=true');
                // if legal notices page w/policySelect, also pass which policy is selected
                // bound to custom event "policy:set" that's triggered in policySelect.js
                if ($('#policySelect').length) {
                    $(window).bind('policy:set', function() {
                        var selectedPolicy = $('#policySelect option:selected').val().replace(/\./g, '');
                        if (selectedPolicy !== 0) {
                            printUrl = $.param.querystring(printUrl, ('policy=' + selectedPolicy));
                        }
                    });
                }
                _printTitle = $.param.querystring(document.title + ' - Printable');
                $('#print').bind('click', function() {

                    Tracker.trackClick('print', 'print', {
                        prop1: Tracker.prefix + 'print',
                        prop5: 'print: ' + document.title.replace(/[^A-Za-z0-9 ]*/ig, '').toLowerCase()
                    });

                    window.open(printUrl, _printTitle, '');
                });
            }
        }
        /*
        * Open printable versions of different printable modal dialogs.
        */
        function _openModalPrintWin(modalID) {
            var qs = '';
            if (modalID) {
                switch (modalID) {
                    case 'nutritionFactsModal':
                        qs = 'print=nutrition';
                        break;
                    case 'ingredDetailsModal':
                        qs = 'print=ingredients';
                        break;
                    case 'frescoTestingModal':
                        qs = 'print=fresco';
                        break;
                    case 'mobileTroubleshootModal':
                        qs = 'print=troubleshoot';
                        break;
                    default:
                        break;
                }
            }
            if (qs !== '') {
                var winURL = $.param.querystring(window.location.href, qs);
                window.open(winURL, (modalID + 'print'), '');
            }
        }
        return {
            setUpPrintable: function() {
                _setUpPrintable();
            },
            setUpPrintBtn: function() {
                _setUpPrintBtn();
            },
            openModalPrintWin: function(modalID) {
                _openModalPrintWin(modalID);
            }
        };
    })();
}

/*
* Global page initialization.
*/
$(window).load(function() {
    if (tacoBell.isPrintable) {
        tacoBell.utils.PrintManager.setUpPrintable();
    } else {
        tacoBell.utils.PrintManager.setUpPrintBtn();
    }
});
$(document).ready(function() {
    if (!tacoBell.isPrintable) {
        tacoBell.utils.RolloverManager.setUp();
        tacoBell.utils.ModalDialogManager.setUp();
        tacoBell.utils.ShareManager.setUp();
        $('#linkRelated').bind('click', function(event) {
            event.preventDefault();
            tacoBell.utils.ModalDialogManager.openModal('relatedSites');
        });
        $('#findUsZip').one('focus', function() {
            $(this).attr('value', '');
        });
        $('#findUsZipGo').click(function() {
            $('#fmStoreLocator').submit();
        });
    }
});

$(function()
{
	var exitOver = function()
	{
		var o = $(this).offset(),
			v = 'site_intl',
			d = 'arrow_left',
			t = $(this).width();
		
		if ($(this).hasClass('3rd'))
			v = 'site_3rd';
		
		if (o.left + 200 > $(window).width() / 2)
		{
			d = 'arrow_right';
			t = v == 'site_intl'? -295 : -415;
		}
		
		$('#exit_tooltip')
			.css({
				left: o.left + t,
				top: Math.max(0, ($(this).height() / 2) + o.top - (d == 'arrow_right'? 48 : 52))
			})
			.removeClass(d == 'arrow_left'? 'arrow_right' : 'arrow_left')
			.addClass(d)
			.removeClass(v == 'site_intl'? 'site_3rd' : 'site_intl')
			.addClass(v)
			.show();
	}
	
	var exitOut = function()
	{
		$('#exit_tooltip').hide();
	}
	
	window.ExitLinkController = {
		scan: function()
		{
			$('a.exit_link')
				.unbind('mouseover', exitOver)
				.unbind('mouseout', exitOut)
				.bind('mouseover', exitOver)
				.bind('mouseout', exitOut);
		}
	};
	
	ExitLinkController.scan();
});