﻿/// <reference path="jquery-1.3.2.js" />

var parseSelector = $;  // allows us to use jquery selectors with sIFR

$(document).ready(function() {
    if (InLiveMode()) {
        if ($('.bp-Home').length > 0)
            $('.bp-Carousel').carousel({ itemsPerAnim: 3 });
        else
            $('.bp-Carousel').carousel({ itemsPerAnim: 2, itemsPerSlide: 2 });
        //$('div:not(.bp-Home) .bp-Carousel').carousel({ itemsPerAnim: 2, itemsPerSlide: 2 });

        $('.jq-Preview').preview();
        $('.bp-Button').button();
        InitHTMLElements();
        InitExternalLinks();
        InitLocationFinder();
        InitGalleries();
        InitDefuscation();
        InitVideoLinks();
    }
});

InitVideoLinks = function() {
    var maxHeight = 300;
    var maxWidth = 450;
    var decrease_w, decrease_h, decrease_total;
    var h, w;
    var html, title;

    $('a[rel*=video]').click(function(e) {
        title = $(this).attr('title');
        $.getJSON('http://vimeo.com/api/oembed.json?url=' + $(this).attr('href') + '&callback=?',
            function(data) {
                if ((data.width > maxWidth) || (data.height > maxHeight)) {
                    // if dimensions are bigger than are desired max/width then we will proportionately
                    // size the video down to fit.
                    if (data.width > maxWidth)
                        decrease_w = Math.floor((maxWidth / data.width) * 100);
                    if (data.height > maxHeight)
                        decrease_h = Math.floor((maxHeight / data.height) * 100);

                    decrease_total = ((decrease_w > decrease_h) ? decrease_w : decrease_h) / 100;
                    h = Math.floor(data.height * decrease_total);
                    w = Math.floor(data.width * decrease_total);

                    // search and replace height/width parameters of output html
                    html = data.html.replace('height="' + data.height + '"', 'height="' + h + '"').replace('width="' + data.width + '"', 'width="' + w + '"');
                }
                else {
                    // Otherwise just use the raw dimensions of the vid
                    w = data.width;
                    h = data.height;
                    html = data.html;
                }

                html = '<h2 class="sIFRDisabled">' + title + '</h2><div class="bp-VideoContainer">' + html + '</div>';
                $.modal(html, { maxHeight: parseInt(h), maxWidth: parseInt(w), onClose: function(dialog) { $(dialog.container).find('.simplemodal-data').empty(); $.modal.close(); } });
            });
        return false;
    });
}

InitSIFRParseSelector = function() {
    // jquery not selector doesn't seem to work properly, implementing custom
    parseSelector.pseudoClasses = {
        'not': function(nodes, selector) {
            var result = [];
            each: for (var i = 0, node; i < nodes.length; i++) {
                node = nodes[i];
                var ignore = parseSelector(selector, node.parentNode);
                for (var j = 0; j < ignore.length; j++) {
                    if (ignore[j] == node) continue each;
                }
                result.push(node);
            }
            return result;
        }
    };
}

InitHTMLElements = function() {
    // "first" headings
    $('.bp-Section h2:first, .bp-Content1 h2:first, .bp-Content2 h2:first').addClass('first');


    // hr replacement
    $('hr').each(function() {
        if (!$(this).parent().hasClass('hr'))
            $(this).wrap('<div class="hr"></div>');
    });


    // columns
    $('.bp-Columns').find('.bp-Column:last').addClass('bp-Column-Last');
    if ($.browser.msie && $.browser.version <= 6)
        $('.bp-Columns').append('<div class="clearBoth"></div>');


    // interior pages
    if ($('.bp-Interior .bp-Content1 .bp-Photo').length > 0)
        $('.bp-Interior .bp-Content1 h1').addClass('bp-WithPhoto');


    // check for headings too long
    $('.bp-Interior h1').each(function() {
        if ($(this).height() > 100) {
            $(this).addClass('multiline');
        }
    });
}

InitGalleries = function() {
    galleries = new Array();
    $('.bp-GalleryPhotos').each(function(i) {
        galleries[i] = new ImageGallery($(this).attr('id'), i);
    });
}

InitExternalLinks = function() {
    $('a[rel=external]').click(function() {
        OpenExternalUrl(this.href);
        return false;
    });
}

OpenExternalUrl = function(url) {
    var external = window.open(url);
    external.focus();
}

InitLocationFinder = function() {
    var selected = ($('.bp-LocationFinder-Selected').length > 0);
    var selector = '';

    if (selected) { selector = '.bp-LocationFinder .bp-LocationFinder-Header .title'; }
    else { selector = '.bp-LocationFinder .bp-LocationFinder-Header'; }

    $(selector + ', .bp-LocationFinder .bp-LocationFinder-Controls a.close').click(function(e) {
        var body = $(this).closest('.bp-LocationFinder').children('.bp-LocationFinder-Body');
        var marginTop = parseInt(body.css('margin-top').replace('px', ''));

        var height;
        var expand = (body.height() == 0);

        if (expand) {
            marginTop += (selected) ? 25 : 38;
            height = (selected) ? '127px' : '140px';
            if (selected) $('.bp-LocationFinder .title').hide();
        }
        else {
            marginTop = (selected) ? -60 : -70;
            height = 0;
            body.parent().removeClass('bp-LocationFinder-Expanded bp-LocationFinder-Expanded-Selected');
        }

        body.animate({
            marginTop: marginTop + 'px',
            height: height
        }, function() { if (expand) { if (selected) body.parent().addClass('bp-LocationFinder-Expanded-Selected'); body.parent().addClass('bp-LocationFinder-Expanded'); body.find('input:first').select().trigger('click'); } else { if (selected) $('.bp-LocationFinder .title').show(); } });

    });


    $('input.bp-Query-City').autocomplete(bp_Cities);
    $('input.bp-Query-City').result(LocationAutocompleteSelected);


    $('.bp-LocationFinder-Controls a.search').click(function(e) {
        var frm = $('.bp-LocationFinder .bp-Form');
        var postalcode = frm.find('input.postalCode').val();
        var url = ServiceUrls.Locations;

        if (postalcode != '') {
            var distance = frm.find('.distance').val();
            url += GenerateQueryStringElement('postalCode', postalcode.toLowerCase(), url);
            url += GenerateQueryStringElement('distance', distance, url);
        }
        else {
            var city = frm.find('input:first').val().split(', ')[0];
            var prov = frm.find('.province').val();

            url += GenerateQueryStringElement('city', city.toLowerCase(), url);
            url += GenerateQueryStringElement('prov', prov, url);
        }

        $(this).attr('href', url);  //reset URL to include form elements on qstring
    });

    /*$('.bp-LocationFinder input').bind('keypress', function(e) {
    if (!e) var e = window.event;
    if (e.keyCode == 13) {
    e.cancelBubble = true;
    e.returnValue = false;
    return false;
    }
    });*/
}

GenerateQueryStringElement = function(key, val, url) {
    var qsItem = '';

    if (val != '') {
        val = encodeURIComponent(val);
        if (url.indexOf('?') > 0)
            qsItem = '&' + key + '=' + val;
        else
            qsItem = '?' + key + '=' + val;
    }
    return qsItem;
}

LocationAutocompleteSelected = function(event, data) {
    data = String(data);
    if (data.indexOf(', ') > 0) {
        var prov = data.split(", ")[1];
        if (prov != 'undefined') {
            $(this).parents('fieldset').find('select.province').val(prov.toLowerCase()); // auto-populate province dropdown
            $(this).val(String(data).split(", ")[0]);
        }
    }
}

InitSIFR = function(color)
{
    if (parseSelector.pseudoClasses['not'] == null)
        InitSIFRParseSelector(); // use custom 'not' selector
    
    // Check to see if the optional color parameter has been passed in or not
    if (undefined === color)
    {
        switch (selectedTheme.toLowerCase())
        {
            case 'orange':
                color = '#df7422';
                break;
            case 'green':
                color = '#739c4b';
                break;
            case 'yellow':
                color = '#e9bc25';
                break;
            default:
                color = '#0e4377';
                break;
        }
    }
    else
    {
        // Ensure that the color passed in is a hex string and not its RGB equivalent
        color = RGBtoHEX(color);
    }


    if (clarendon != 'undefined')
    {
        sIFR.replace(clarendon, {
            selector: 'h1.sIFR, .bp-Store h1 span',
            css: {
                '.sIFR-root': { 'color': '#ffffff', 'font-weight': 'bold' }
            },
            wmode: 'transparent'
        });


        sIFR.replace(clarendon, {
            selector: '.bp-GiftCards .bp-Content1 h2',
            css: [
                  '.sIFR-root { color: #d12321; font-weight: bold; }'
                  , 'a { text-decoration: none; }'
                  , 'a:link { color: #d12321; }'
                  , 'a:hover { color: #000000; }'
                ],
            wmode: 'transparent'
        });

        sIFR.replace(clarendon, {
                selector: '.bp-Content1 h2:not(.sIFRDisabled), .bp-Content2 h2, .bp-Content3 h2, .bp-WorkAtBP h3',
                css: [
                      '.sIFR-root { color: ' + color + '; font-weight: bold; }'
                      , 'a { text-decoration: none; }'
                      , 'a:link { color: #d12321; }'
                      , 'a:hover { color: #000000; }'
                    ],
                wmode: 'transparent'
            });
    };

}

//Function to convert rgb() format values into normal hex values
RGBtoHEX = function(str)
{
    if (str.substring(0, 3) == 'rgb')
    {
        var arr = str.split(",");
        var r = arr[0].replace('rgb(', '').trim(), g = arr[1].trim(), b = arr[2].replace(')', '').trim();
        var hex = [
			toHex(r),
			toHex(g),
			toHex(b)
		];
        return "#" + hex.join('');
    }
    else
    {
        return str;
    }
}

toHex = function(N)
{
    if (N == null) return "00";
    N = parseInt(N); if (N == 0 || isNaN(N)) return "00";
    N = Math.max(0, N); N = Math.min(N, 255); N = Math.round(N);
    return "0123456789ABCDEF".charAt((N - N % 16) / 16)
      + "0123456789ABCDEF".charAt(N % 16);
}


InLiveMode = function() {
    return ($('.bp-EditMode').length < 1 && $('.bp-PreviewMode').length < 1);
}


/* email defuscate */


/*
will scan page for obfuscated emails and vcards and convert them to properly
formed URLs
*/

InitDefuscation = function() {
    $("a.email[href*='(at)']").emailDefuscate().css('visibility', 'visible'); //email addys
}

convertAddyHref = function(el, email) {
    $(el).attr('href', 'mailto:' + email);
}



$.fn.button = function() {
    return this.each(function() {
        var el = $(this);
        el.append('<span></span>');
    });
}

$.fn.stripHTML = function() {
    var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
    this.each(function() {
        $(this).html(
			$(this).html().replace(regexp, "")
		);
    });
    return $(this);
}
$.fn.emailDefuscate = function() {
    return this.each(function() {
        var el = $(this);
        var href = el.attr('href').split('/');
        var email = String(href[href.length - 1]).replace(/\s*\(.+\)\s*/, "@");
        var innerHTML = String(el.html().replace(/\s*\(.+\)\s*/, "@"));

        el.attr('href', 'javascript: void(0);').click(function() {
            convertAddyHref(this, email);
        });

        el.html(innerHTML);
    });
}

$.fn.hasRel = function(s) {
    var arrRel = $(this).attr('rel').split(' ');
    return ($.inArray(s, arrRel) != -1 ? true : false);
}