/* Author: Craig MacKenzie */

var windowURL = window.location.toString();

if(windowURL.search('https') == -1) window.location.replace(windowURL.replace('http', 'https'));

if (window.location)

// language finder
function langType(){
    var url = window.location.pathname;
    if (url.match('/en/')) {
        return 'EN';
    }
    else 
        if (url.match('/fr/')) {
            return 'FR';
        }
        else {
            // if something unexpected happens default to English
            return 'EN';
        }
}

// dynamic javascript text
var cara_text = {
    'EN': {
        'error': 'Error',
        'thanks': 'Success',
        'emailSyntax': 'The format of your email address is incorrect. Please re-enter your email.',
        'alreadyRegistered': 'This email address is already registered.',
        'emailSuccess': 'Thanks for registering with Bon Appétit Gift Cards.'
    },
    'FR': {
        'error': 'Erreur',
        'thanks': 'Succès',
        'emailSyntax': 'Le format de l’adresse de courriel fournie est incorrect.\n Veuillez réinscrire votre adresse de courriel. ',
        'alreadyRegistered': 'Cette adresse de courriel est déjà inscrite.',
        'emailSuccess': 'Thanks for registering with Bon Appétit Gift Cards.'
    },
    'pageTitle': document.title
}

/* notice for safari browser */
function showSafariNotice(){
    var browserNotice = {
        'EN': '<div id="BrowserNotice"><em>The functionality of this website is supported by <a href="http://www.mozilla.com/en-US/firefox/personal.html" title="Click here to download">Firefox</a>, <a href="http://www.microsoft.com/windows/internet-explorer/worldwide-sites.aspx" title="Click here to download">Internet Explorer 7+</a> and <a href="http://www.google.com/chrome" title="Click here to download">Google Chrome</a>. Please use any of these free, easy-to-download browsers for the best Bon Appétit Gift Card experience. We apologize for any inconvenience. <a href="http://www.mozilla.com/en-US/firefox/personal.html" class="icon firefox" title="Click here to download">Firefox</a><a href="http://www.microsoft.com/windows/internet-explorer/worldwide-sites.aspx" class="icon IE" title="Click here to download">Internet Explorer</a><a href="http://www.google.com/chrome" class="icon chrome" title="Click here to download">Chrome</a></em></div>',
        'FR': '<div id="BrowserNotice"><em>La fonctionnalité de ce site Internet est soutenue par <a href="http://www.mozilla.com/en-US/firefox/personal.html" title="Télécharger">Firefox</a>, <a href="http://www.microsoft.com/windows/internet-explorer/worldwide-sites.aspx" title="Télécharger">Internet Explorer 7+</a> et <a href="http://www.google.com/chrome" title="Télécharger">Google Chrome</a>. Servez-vous de l’un de ces navigateurs gratuits et faciles à Télécharger pour vivre la meilleure des expériences sur le site de la carte-cadeau Bon Appétit! Nous nous excusons pour tout inconvénient. <a href="http://www.mozilla.com/en-US/firefox/personal.html" class="icon firefox" title="Télécharger">Firefox</a><a href="http://www.microsoft.com/windows/internet-explorer/worldwide-sites.aspx" class="icon IE" title="Télécharger">Internet Explorer</a><a href="http://www.google.com/chrome" class="icon chrome" title="Télécharger">Chrome</a></em></div>'
    }
    // prepend safari notice
    $('body').prepend(browserNotice[langType()]);
    var notice = $('#BrowserNotice');
    var wrapper = $('#Wrapper');
    // animate notice down
    notice.css({
        'top': notice.outerHeight() * -1,
        display: 'block'
    }).animate({
        top: 0
    }, 400, 'swing');
    // animate wrapper down
    wrapper.css({
        'margin-bottom': notice.outerHeight()
    }).animate({
        top: notice.outerHeight()
    }, 400, 'swing');
}

/* notice for IE6 browser */
function showIE6Notice(){
    var browserNotice = {
        'EN': '<div id="BrowserNotice"><em>The functionality of this website is supported by <a href="http://www.mozilla.com/en-US/firefox/personal.html" title="Click here to download">Firefox</a>, <a href="http://www.microsoft.com/windows/internet-explorer/worldwide-sites.aspx" title="Click here to download">Internet Explorer 7+</a> and <a href="http://www.google.com/chrome" title="Click here to download">Google Chrome</a>. Please use any of these free, easy-to-download browsers or upgrade your current browser for the best Bon Appétit Gift Card experience. We apologize for any inconvenience. <a href="http://www.mozilla.com/en-US/firefox/personal.html" class="icon firefox" title="Click here to download">Firefox</a><a href="http://www.microsoft.com/windows/internet-explorer/worldwide-sites.aspx" class="icon IE" title="Click here to download">Internet Explorer 7+</a><a href="http://www.google.com/chrome" class="icon chrome" title="Click here to download">Chrome</a></em></div>',
        'FR': '<div id="BrowserNotice"><em>La fonctionnalité de ce site Internet est soutenue par <a href="http://www.mozilla.com/en-US/firefox/personal.html" title="Télécharger">Firefox</a>, <a href="http://www.microsoft.com/windows/internet-explorer/worldwide-sites.aspx" title="Télécharger">Internet Explorer</a> et <a href="http://www.google.com/chrome" title="Télécharger">Google Chrome</a>. Servez-vous de l’un de ces navigateurs gratuits et faciles à Télécharger ou mettez à niveau votre navigateur actuel pour vivre la meilleure des expériences sur le site de la carte-cadeau Bon Appétit! Nous nous excusons pour tout inconvénient. <a href="http://www.mozilla.com/en-US/firefox/personal.html" class="icon firefox" title="Télécharger">Firefox</a><a href="http://www.microsoft.com/windows/internet-explorer/worldwide-sites.aspx" class="icon IE" title="Télécharger">Internet Explorer</a><a href="http://www.google.com/chrome" class="icon chrome" title="Télécharger">Chrome</a></em></div>'
    }
    // prepend safari notice
    $('body').prepend(browserNotice[langType()]);
    var notice = $('#BrowserNotice');
    var wrapper = $('#Wrapper');
    // animate notice down
    notice.css({
        'top': notice.outerHeight() * -1,
        display: 'block'
    }).animate({
        top: 0
    }, 400, 'swing');
    // animate wrapper down
    wrapper.css({
        'margin-bottom': notice.outerHeight()
    }).animate({
        top: notice.outerHeight()
    }, 400, 'swing');
}

// check URL for language param
// swap language param and redirect
function langToggle(){
    var url = window.location.pathname;
    if (langType() == 'EN') {
        window.location = url.replace('/en/', '/fr/');
    }
    if (langType() == 'FR') {
        window.location = url.replace('/fr/', '/en/');
    }
};

// set cross domain iFrame height
function setiFrameHeight(){
    $('#givexTemplate').css({
        'position': 'absolute',
        'left': '-99999px'
    });
    $('#iFrame_ph').css({
        'display': 'block'
    })
    
    var hashValue = window.location.hash;
    if (hashValue.length < 1) {
        $('#iFrame_ph').css({
            'display': 'none'
        })
        $('#givexTemplate').css({
            'height': hashValue,
            'position': 'relative',
            'left': '0px',
            'height': '1000px'
        });
    }
    else {
        hashValue = parseInt(hashValue.replace("#", "")) + 48;
        hashValue = hashValue + "px";
        $('#iFrame_ph').animate({
            'height': hashValue
        }, 300, "swing", function(){
            $(this).css({
                'display': 'none'
            })
            $('#givexTemplate').css({
                'height': hashValue,
                'position': 'relative',
                'left': '0px'
            });
        })
        
        if (navigator.appName.match("Microsoft") != null || navigator.userAgent.match("Chrome") != null) {
            // This is to reset the page title in IE
            // for some reason the # sign was being appended to to it.
            document.title = unescape(cara_text.pageTitle);
        }
        else {
            // removes hash set by givex iFrame so the user doesn't have to 
            // click back twice to get to the previous page. 
            history.back(1);
        }
    }
}

// subscribe ajax functionality
function subscribeUser(){
    // subscribe web service url
    var subscribeAppURL = '/webapps/subscribe/Default.ashx';
    // on subscribe submission
    $('#emailSubscribe').submit(function(){
        showFullOverlay('processing', .5, "#000");
        var emailData = $('#emailSubscribe').serialize();
        $.post(subscribeAppURL, emailData, function(data){
            // Process response data
            setTimeout(function(){
                $('#processing').hide();
                if ($(data).find('success').text() == '0') {
                    $('#processing').hide();
                    if ($(data).find('item').attr('key') == 'email') {
                        $('#Result h1').text(cara_text[langType()].error);
                        $('#Result p').text(cara_text[langType()].emailSyntax);
                    }
                    else {
                        $('#Result h1').text(cara_text[langType()].error);
                        $('#Result p').text(cara_text[langType()].alreadyRegistered);
                    }
                }
                else {
                    $('#Result h1').text(cara_text[langType()].thanks);
                    $('#Result p').text(cara_text[langType()].emailSuccess);
                }
                $('#Result').show();
            }, 1000)
            
        });
        return false;
    });
    inputAutoSelect('#email');
    // allow user to close box when finished
    $('a.closer').click(function(){
        var noticeID = $(this).parent('div').attr('id');
        hideFullOverlay(noticeID);
    })
    
}

// shows full window overlay.
function showFullOverlay(noticeID, opacityVal, color){
    $('select').addClass("hide_select"); // This is for IE6 only
    $('#flash_carousel').css({
        'visibility': 'hidden'
    });
    if (location.pathname.match('DesignYourOwn.aspx')) {
        $('#givexTemplate').css({
            'visibility': 'hidden'
        });
    }
    $('div.overlay').css({
        display: "block",
        height: $(document).height(),
        width: $(document).width(),
        opacity: opacityVal,
        backgroundColor: color
    });
    $('div#' + noticeID).css({
        display: "block"
    })
};

// hide full overlay
function hideFullOverlay(noticeID){
    $('select').removeClass("hide_select"); // This is for IE6 only
    $('#flash_carousel, #givexTemplate').css({
        'visibility': 'visible'
    });
    $('div.overlay').css({
        display: "none"
    });
    $('div#' + noticeID).css({
        display: "none"
    })
};

//open out going links (http:// prefix) in a new window
function openHTTPlinksInNewWindow(){
    $('a[href^="http://"]').each(function(){
        $(this).attr({
            target: "_blank",
            title: $(this).attr('title') + ' - Opens in a new window.'
        });
    });
}

// add divider elements to specifid element(s)
function addDivider(element, divider, startIndex, endIndex){
    if (divider == undefined) 
        divider = $('<li>|</li>');
    var dividerElement = $(divider);
    if (startIndex == undefined) 
        startIndex = 0;
    if (endIndex == undefined) {
        $(element + ':gt(' + startIndex + ')').before(dividerElement);
    }
    else {
        for (i = startIndex; i <= endIndex; i++) {
            $(element).eq(i).before(dividerElement);
        }
    }
}

// autoselect target input contents
function inputAutoSelect(target){
    $(target).focus(function(){
        $(target).select();
    })
}

// used for showing active links (so far only used in links contained within a SSI)
function showActiveLink(menuWrapper){
    var deepLink = location.pathname;
    menuWrapper = $(menuWrapper);
    if (menuWrapper.length > 0) {
        menuWrapper.find('a[href="' + deepLink + '"]').attr({
            'active': 'true',
            'class': 'active'
        });
    }
}

// slide notice popup when scrolling the window
function boxSlide(){
    var boxTopCss = 170; // Make sure the css top property for div.notice is the same value
    var boxesToSlide = $('div.notice, #Result');
    var previewOffset;
    $(window).scroll(function(){
        previewOffset = getYOffset() + boxTopCss;
        boxesToSlide.stop().animate({
            'top': previewOffset
        }, 400, "swing");
    });
}

function getYOffset(){
    var pageY;
    if (typeof(window.pageYOffset) == 'number') {
        pageY = window.pageYOffset;
    }
    else {
        pageY = document.documentElement.scrollTop;
    }
    return pageY;
}

// animate buy now promo
function animatePromo(){
    if ($('.buyNow').length > 0) {
        var originalH = parseInt($('.buyNow').css('height').replace('px', ''));
        var intervalTime = 5000;
        // animate promo
        animatePromo2(originalH)
        // set initial interval
        var t = setInterval(function(){
            animatePromo2(originalH)
        }, intervalTime);
        
        // clear interval on rollover
        $('.buyNow').hover(function(){
            clearInterval(t);
        }, function(){
            // set interval on rollout
            t = setInterval(function(){
                animatePromo2(originalH)
            }, intervalTime);
        })
    }
    // promo animation
    function animatePromo2(originalH){
        $('.buyNow').animate({
            'height': originalH + 10
        }, 300, 'swing').animate({
            'height': originalH
        }, 300, 'swing').animate({
            'height': originalH + 10
        }, 300, 'swing').animate({
            'height': originalH
        }, 300, 'swing');
    }
}

// check brower
function checkBrowser(){
    var browser;
    if (window.XMLHttpRequest) {
        if (document.expando) {
            browser = 'IE7';
        }
        else 
            if (window.devicePixelRatio && escape(navigator.javaEnabled.toString()) != 'function%20javaEnabled%28%29%20%7B%20%5Bnative%20code%5D%20%7D') {
                browser = 'safari'
            }
            else {
                browser = 'moz, chrome'
            }
    }
    else {
        browser = 'IE6';
    }
    return browser;
}


// page ready functions
function pageSetup(){
    // Show notice to Safari users
    if (checkBrowser() == 'safari') {
        showSafariNotice();
    }
    
    // Show notice to IE6 users
    if (checkBrowser() == 'IE6') {
        showIE6Notice();
    }
    // user subsribe
    subscribeUser();
    // pop window slide
    boxSlide();
    // attach target="_blank" to out going links
    openHTTPlinksInNewWindow();
    // add pipes to footer nav
    addDivider('.footer ul li', '<li>|</li>', 2);
    addDivider('#subNav li');
    // Add active states to sub content menu
    showActiveLink('.supportMenu');
    // Toggle language
    $('a.langToggle').click(function(){
        langToggle();
        return false;
    });
    // add break lines to TAF form
    if ($('ul.TAF').length > 0) {
        $('ul.TAF li:nth-child(2n)').addClass('break')
    }
}

// page load functions
function init(){
    animatePromo();
}

// initalizes page load functions
window.onload = init;

var BrowserDetect = {
    init: function(){
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent) ||
        this.searchVersion(navigator.appVersion) ||
        "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function(data){
        for (var i = 0; i < data.length; i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1) 
                    return data[i].identity;
            }
            else 
                if (dataProp) 
                    return data[i].identity;
        }
    },
    searchVersion: function(dataString){
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) 
            return;
        return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
    },
    dataBrowser: [{
        string: navigator.userAgent,
        subString: "Chrome",
        identity: "Chrome"
    }, {
        string: navigator.userAgent,
        subString: "OmniWeb",
        versionSearch: "OmniWeb/",
        identity: "OmniWeb"
    }, {
        string: navigator.vendor,
        subString: "Apple",
        identity: "Safari",
        versionSearch: "Version"
    }, {
        prop: window.opera,
        identity: "Opera"
    }, {
        string: navigator.vendor,
        subString: "iCab",
        identity: "iCab"
    }, {
        string: navigator.vendor,
        subString: "KDE",
        identity: "Konqueror"
    }, {
        string: navigator.userAgent,
        subString: "Firefox",
        identity: "Firefox"
    }, {
        string: navigator.vendor,
        subString: "Camino",
        identity: "Camino"
    }, { // for newer Netscapes (6+)
        string: navigator.userAgent,
        subString: "Netscape",
        identity: "Netscape"
    }, {
        string: navigator.userAgent,
        subString: "MSIE",
        identity: "Explorer",
        versionSearch: "MSIE"
    }, {
        string: navigator.userAgent,
        subString: "Gecko",
        identity: "Mozilla",
        versionSearch: "rv"
    }, { // for older Netscapes (4-)
        string: navigator.userAgent,
        subString: "Mozilla",
        identity: "Netscape",
        versionSearch: "Mozilla"
    }],
    dataOS: [{
        string: navigator.platform,
        subString: "Win",
        identity: "Windows"
    }, {
        string: navigator.platform,
        subString: "Mac",
        identity: "Mac"
    }, {
        string: navigator.userAgent,
        subString: "iPhone",
        identity: "iPhone/iPod"
    }, {
        string: navigator.platform,
        subString: "Linux",
        identity: "Linux"
    }]

};
BrowserDetect.init();




$(document).ready(function(){
    // intialize page ready functions
    pageSetup();
});
