﻿/* === depends on jQuery 1.4.2  === */

/*== configuration for JSLint validation (http://www.jslint.com/) ==*/
/*jslint white: true, browser: true, undef: true, eqeqeq: true, bitwise: true, newcap: true, immed: true */
/*global jQuery: false, $: false, window: false, ActiveXObject: false, _gaq: false */

/* Our JavaScript payload is split into two files core (this file) & core-post. Core contains all 
    functionality required to load the page, while core-post contains additional functionality that 
    enhances the page/site but is not absolutely requried for the page to load. When the page has 
    completed loading (window.onload), we asynchronously get & execute the core-post file.
    
    Additionaly there is a core-ie file which is loaded only for IE6 & IE7 which contains various
    fixes and workarounds for IE specific issues.
*/

/* === jquery plugins. These are generic enough that they can be used on other sites. === */
(function ($) {
    $.cookie = function (name, value, options) {
        var cookies,                //array of cookies (e.g. domCookie.split)
            cookie,                 //one cookie (e.g. 'name=value')
            cookieValue = null,
            expires, len, i, date;

        if (value !== undefined) { 
            options = options || {};
       
            if (value === null) {
                options.expires = -1;
            }

            if (options.expires) {
                if (typeof options.expires === 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                    expires = date;
                } else if (options.expires.toUTCString) {
                    expires = options.expires;
                } else {
                    expires = null;
                }
            }

            cookie = name + '=' + (value === null ? '' : encodeURIComponent(value));    //name & value
            cookie += (expires ? ('; expires=' + expires.toUTCString()) : '');          //expires
            cookie += (options.path ? ('; path=' + options.path) : '');             //path
            if (window.location.hostname !== 'localhost') {
                cookie += (options.domain ? ('; domain=' + options.domain) : '');       //domain
            }
            cookie += (options.secure ? '; secure' : '');                               //secure
            document.cookie = cookie;
        } else {
            cookies = document.cookie ? document.cookie.split(';') : [];            
            for (i = 0, len = cookies.length; i < len; i++) {
                cookie = cookies[i];
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break; //found it, so stop looking
                }
            }

            return cookieValue;
        }
    };
}(jQuery));

/* === hmsa.com specific functionality (won't work on other sites) === */
var hmsa = {};

/* a very basic flash detection & embeding implementation (only supports Flash 7+) */
hmsa.flash = (function () {
    var _version = [0, 0, 0],
        _checked = false,
        _flashPluginDescription = 'Shockwave Flash',
        _flashMIMEType = 'application/x-shockwave-flash',
        _flashActiveX = 'ShockwaveFlash.ShockwaveFlash.7';

    function _parseVersion(version, delim) {
        var v = version.split(delim || '.');
        return [(parseInt(v[0], 10)), (parseInt(v[1], 10) || 0), (parseInt(v[2], 10) || 0)];
    }

    function _getFlashVersion() {
        var type, plugin, desc, axo;

        if (!_checked) {
            if (navigator.mimeTypes !== undefined && navigator.plugins !== undefined && navigator.plugins.length > 0) {
                type = navigator.mimeTypes[_flashMIMEType];
                plugin = navigator.plugins[_flashPluginDescription];

                if (type !== undefined && plugin !== undefined && type.enabledPlugin) {
                    //desc = 'Shockwave Flash 10.0 r2' to '10.0 r2'
                    desc = plugin.description.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
                    _version[0] = parseInt(desc.replace(/^(.*)\..*$/, "$1"), 10);
                    _version[1] = parseInt(desc.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
                    _version[2] = /[a-zA-Z]/.test(desc) ? parseInt(desc.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0;
                }
            } else if (window.ActiveXObject !== undefined) {
                try {
                    axo = new ActiveXObject(_flashActiveX);
                    _version = _parseVersion(axo.GetVariable("$version").split(' ')[1], ',');
                } catch (e) { }
            }

            _checked = true;
        }

        return _version;
    }

    function hasFlash(version) {
        _getFlashVersion();

        var d = _parseVersion(version || '8.0.0');  //desired version, defaulting to 8
        var a = _version;                           //actual version

        return (a[0] > d[0]) || (a[0] === d[0] && a[1] > d[1]) || (a[0] === d[0] && a[1] === d[1] && a[2] >= d[2]);
    }

    function getEmbedHtml(movie, attributes, parameters, fallback) {
        var i, html = '<object data="' + movie + '" type="' + _flashMIMEType + '" ';

        if (attributes !== undefined) {
            for (i in attributes) {
                if (attributes[i] !== Object.prototype[i]) {
                    html += i + '="' + attributes[i] + '" ';
                }
            }
        }

        html += '>\n\t<param name="movie" value="' + movie + '" />\n';

        if (parameters !== undefined) {
            for (i in parameters) {
                if (parameters[i] !== Object.prototype[i]) {
                    html += '\t<param name="' + i + '" value="' + parameters[i] + '" />\n';
                }
            }
        }

        if (fallback !== undefined) {
            html += '\t' + fallback;
        }

        return html + '\n</object>';
    }
    
    function embed(id, movie, attributes, parameters, fallback) {
        var $target = $('#' + id);
        var params = jQuery.extend({
            allowScriptAccess: 'sameDomain', 
            wmode: 'transparent'
        }, parameters);

        fallback = (fallback === undefined) ? $target.html() : $('#' + fallback).html();

        $target.html(getEmbedHtml(movie, attributes, params, fallback));
    }

    return { hasFlash: hasFlash, getEmbedHtml: getEmbedHtml, embed: embed };
}());

/* sifr */
hmsa.sifr = (function () {
    var _enabled = hmsa.flash.hasFlash('8.0.0');
    var settings = {
        minWidth: 514,
        sifrClass: 'sifr',
        sifrReplacedClass: 'sifr-replaced',
        sifrFallbackClass: 'sifr-fallback',
        swfPath: '/res/flash/sifr.swf'
    };

    function replaceHeaders() {
        if (!_enabled) {
            return;
        }

        $('.' + settings.sifrClass).each(function () {
            var $this = $(this);
            var t = this.innerHTML;                                                                 //text
            var w = (settings.minWidth < this.offsetWidth) ? settings.minWidth : this.offsetWidth;  //width
            var h = ($.browser.msie) ? this.offsetHeight - 5 : this.offsetHeight;                   //height
            var flashvars = hmsa.util.getQueryString({ u: true, w: w, t: t, h: h, k: true, s: 0 }); //vars passed to flash
            var attributes = { width: "100%", height: (h + 8) };                                    //attributes of <object>
            var params = { FlashVars: flashvars, bgcolor: '#F2EFEB', wmode: 'opaque' };                              //parameters of <object>
            var embed = hmsa.flash.getEmbedHtml(settings.swfPath, attributes, params);              //<object> html
            var fallback = '<span class="' + settings.sifrFallbackClass + '">' + t + '</span>';     //<span> fallback

            $this
                .html(embed + fallback)
                .removeClass(settings.sifrClass)
                .addClass(settings.sifrReplacedClass);
        });
    }

    function revert() {
        if (!_enabled) {
            return;
        }

        $('.' + settings.sifrReplacedClass)
            .removeClass(settings.sifrReplacedClass)
            .addClass(settings.sifrClass)
            .each(function () {
                var $this = $(this);
                $this.html($this.children('.' + settings.sifrFallbackClass).html());
            });
    }

    function redraw() {
        if (_enabled) {
            revert();
            replaceHeaders();
        }
    }

    return { 
        settings: settings, 
        replaceHeaders: replaceHeaders, 
        revert: revert, 
        redraw: redraw 
    };
}());

/* utilities */
hmsa.util = {
    getQueryString: function (obj) {
        var q = '', name;

        if (typeof obj === 'object') {
            for (name in obj) {
                if (obj.hasOwnProperty(name)) {
                    q += name + '=' + encodeURIComponent(obj[name]) + '&';
                }
            }
            q = (q.length > 0) ? q.substring(0, q.length - 1) : ''; //remove trailing ampersand
        }

        return q;
    },
    loadIframe: function ($iframe) {        
        $iframe
            .load(function () {
                if (this.src) {
                    $(this).show();
                }
            })
            .attr('src', $iframe.attr('rel'));
    }
};



/* search textbox google watermark */
$('#search .textbox')
    .live('focusin focusout init', function (e) {
        var $this = $(this);
        $this.toggleClass('googleMark', e.type !== 'focusin' && $this.val() === '');
        e.stopPropagation();
    })
    .trigger('init');

/* tabs */
$('.tabs').delegate('dt', 'click focus', function () {
    $(this)
        .siblings()
            .removeClass('selected')
            .end()
        .next('dd')
        .andSelf()
        .addClass('selected');
});

/* =toolbar
-----------------------------------------------
    Contains share, print and text resize buttons
-----------------------------------------------*/
(function ($) {
    var sizes = ['normal', 'large', 'xlarge'],  //array of size classes
        cookie = 'cssSize',                     //name of cookie key
        dsi = 0,                                //default size index
        current = dsi,                          //current size index
        methods = {
            print: function () {
                window.print();
            },
            facebook: function () {
            },
            twitter: function () {            
            },
            resize: function () {
                var next = (current + 1) % sizes.length;

                $('body')
                    .removeClass(sizes[current])
                    .addClass(sizes[next]);
                
                //set cookie (delete cookie when on default size, to save on HTTP request size)
                $.cookie(cookie, (next === dsi ? null : sizes[next]), { path: '/', domain: 'hmsa.com' });
                
                //redraw sifr
                hmsa.sifr.redraw();

                //increment current
                current = next;
            },
            email: function () {
                //open email form
                //alert("not implemented");
            }
        };

    $('#toolbar')
        .delegate('a', 'click', function (e) {
            methods[$(this).attr('class')]();
        })
        .find('a')
        .attr('title', function () {
            return $(this).text();
        });

    //get initial size from cookie
    current = $.inArray($.cookie(cookie), sizes);
    current = current >= 0 ? current : dsi;
}(jQuery));

/* document.ready (DOM is ready) */
$(function () {
    hmsa.sifr.replaceHeaders();
});

/* =tracker
---------------------------------------------------------------
    Track links that Google Analytics doesn't handle by default
        -download files (pdf, doc, etc)
        -external links (web & email)
        -share links (email, 
--------------------------------------------------------------*/
hmsa.track = (function ($, _gaq) {
    var ga = _gaq,
        filters = {
            download: function (url) {
                //remove leading slash & domain if it exists
                return '/links/download/' + url.replace(/((https?:\/\/.*?)?\/)/i, '');
            },
            email: function (url) {
                //remove mailto: protocol
                return '/links/email/' + url.replace(/mailto\:/i, '');
            },
            external: function (url) {
                //remove http/https protocol
                return '/links/external/' + url.replace(/(https?:\/\/)/i, '');
            },
            share: function (website) {
                return '/links/share/' + website;
            }
        };
    
    function track(a) {
        var cmd = [];
        
        if (typeof a === 'object' && a.category && a.action) {
            //argument is object, track as event
            cmd.push('_trackEvent', a.category, a.action);
            if (a.opt_label && a.opt_value) {
                cmd.push(a.opt_label, a.opt_value);
            }
        } else if (typeof a === 'string') {
            //argument is string, track as pageview URL         
            cmd.push('_trackPageview', a);
        }

        if (cmd.length) {
            ga.push(cmd);       
        }
    }
    
    $('a.external, a.pdf, a.word, a.twitter, a.facebook, a.email').live('click', function () {
        var $this = $(this),
            href = $this.get(0).href;
        
        //external links
        if ($this.hasClass('external')) {
            track(filters.external(href));
        }
        
        //downloads
        if ($this.is('.pdf, .word')) {
            track(filters.download(href));
        }
        
        //email
        if ($this.hasClass('email')) {
            if ($this.is('.share .email')) {
                track(filters.share('email'));
            } else {
                track(filters.email(href));
            }
        }
        
        //twitter
        if ($this.is('.share .twitter')) {
            track(filters.share('twitter'));
        }
        
        //facebook
        if ($this.is('.share .facebook')) {
            track(filters.share('facebook'));
        }
    });

    return track;
} (jQuery, _gaq));


/* =corepost
--------------------------------------------------------- */
(function ($) {
    /* 
        create a shortcut jquery function to be able to easily
        register for our custom "corepost" event 
    */
    $.extend({
        corepost: function (fn) {
            $('body').bind('corepost', fn);
        }
    });
    
    /* load core-post.js async w/o blocking the page */
    $(window).load(function () {
        /* We use $.ajax over $.getScript because $.getScript appends a timestamp to the 
            querystring which can break caching of the script  */
        $.ajax({
            type: 'GET',
            url: '/res/js/core-post.js',
            dataType: 'script',
            cache: true
        });
    });
}(jQuery));
