/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 */
(function($) {
    // backgroundPosition[X,Y] get hooks
    var $div = $('<div style="background-position: 3px 5px">');
    $.support.backgroundPosition   = $div.css('backgroundPosition')  === "3px 5px" ? true : false;
    $.support.backgroundPositionXY = $div.css('backgroundPositionX') === "3px" ? true : false;
    $div = null;

    var xy = ["X","Y"];

    // helper function to parse out the X and Y values from backgroundPosition
    function parseBgPos(bgPos) {
        var parts  = bgPos.split(/\s/),
            values = {
                "X": parts[0],
                "Y": parts[1]
            };
        return values;
    }

    if (!$.support.backgroundPosition && $.support.backgroundPositionXY) {
        $.cssHooks.backgroundPosition = {
            get: function( elem, computed, extra ) {
                return $.map(xy, function( l, i ) {
                    return $.css(elem, "backgroundPosition" + l);
                }).join(" ");
            },
            set: function( elem, value ) {
                $.each(xy, function( i, l ) {
                    var values = parseBgPos(value);
                    elem.style[ "backgroundPosition" + l ] = values[ l ];
                });
            }
        };
    }

    if ($.support.backgroundPosition && !$.support.backgroundPositionXY) {
        $.each(xy, function( i, l ) {
            $.cssHooks[ "backgroundPosition" + l ] = {
                get: function( elem, computed, extra ) {
                    var values = parseBgPos( $.css(elem, "backgroundPosition") );
                    return values[ l ];
                },
                set: function( elem, value ) {
                    var values = parseBgPos( $.css(elem, "backgroundPosition") ),
                        isX = l === "X";
                    elem.style.backgroundPosition = (isX ? value : values[ "X" ]) + " " +
                                                    (isX ? values[ "Y" ] : value);
                }
            };
            $.fx.step[ "backgroundPosition" + l ] = function( fx ) {
                $.cssHooks[ "backgroundPosition" + l ].set( fx.elem, fx.now + fx.unit );
            };
        });
    }
})(jQuery);

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

(function( $ ){
    $.fn.sadcowtooltip = function( options ) {
        var settings = {
            'alwaysabove'   : false,
            'imagelocation' : '/images/sadcowtooltip',
            'padding'       : 5
        };

        return this.each(function() {
            if ( options ) {
                $.extend( settings, options );
            }

            if ($(this).attr("title") != undefined && $(this).attr("title").length > 1) {
                if ($(this).data('sadcow_title') == undefined) {
                    $(this).data("sadcow_title", $(this).attr("title").replace("\\n", "<br />"));
                    $(this).attr("title", "");
                }
                var title_text = $(this).data('sadcow_title');
                $(this).bind("mouseenter", function() {
                    //measure the element
                    var ewid = $(this).width();
                    var ehei = $(this).width();


                    //measure the tool tip centre
                    $("body").append('<span id="sadcowtooltipmeasure" class="sadcowtooltip" style="float: none; filter:alpha(opacity=0);opacity: 0;-moz-opacity:0;">'+title_text+'</span><br id="sadcowtooltipbr"/>');
                    var owid = wid = $("#sadcowtooltipmeasure").width();
                    var ohei = hei = $("#sadcowtooltipmeasure").height();
                    wid += settings['padding'] * 2;
                    hei += settings['padding'] * 2;

                    $("#sadcowtooltipbr").remove();

                    var offset = $(this).offset();

                    var x = offset.left;
                    var y = offset.top;
                    var toolident = x+'-'+y;
                    $(this).data("sadcow_toolident", toolident);

                    //x -= ((wid+11+14)-(ewid / 2)); // tooltip width plus half of the calling element width
                    x -= Math.round (wid / 2);
                    x += Math.round (ewid / 2);
                    x -= 14;
                    y -= (hei+24);

                    var tip_code = '<div class="sadcowtooltipwrapper '+toolident+'" style="top:'+y+'px; left:'+x+'px;width:'+(wid+11+14)+'px; height:'+(hei+11+20)+'px;">' +

                    '<div style="float:left;width:14px;height:11px;background-image:url('+settings['imagelocation']+'/tooltip-topleft.png);"></div>' +
                    '<div style="float:left;width:'+wid+'px;height:11px;background-image:url('+settings['imagelocation']+'/tooltip-top.png);"></div>' +
                    '<div style="float:left;width:11px;height:11px;background-image:url('+settings['imagelocation']+'/tooltip-topright.png);"></div>' +

                    '<div style="float:left;width:14px;height:'+hei+'px;background-image:url('+settings['imagelocation']+'/tooltip-left.png);"></div>' +
                    '<div class="sadcowtooltip" style="float:left;width:'+owid+'px;height:'+ohei+'px;background-image:url('+settings['imagelocation']+'/tooltip-back.png);padding:'+settings['padding']+'px;">'+title_text+'</div>' +
                    '<div style="float:left;width:11px;height:'+hei+'px;background-image:url('+settings['imagelocation']+'/tooltip-right.png);"></div>' +

                    '<div style="float:left;width:14px;height:20px;background-image:url('+settings['imagelocation']+'/tooltip-bottomleft.png);"></div>' +
                    '<div style="float:left;width:'+wid+'px;height:20px;background-image:url('+settings['imagelocation']+'/tooltip-bottom.png);background-position:center top"></div>' +
                    '<div style="float:left;width:11px;height:20px;background-image:url('+settings['imagelocation']+'/tooltip-bottomright.png);"></div>' +

                    '</div>'

                    $("#sadcowtooltipmeasure").replaceWith(tip_code);
                    $("."+toolident).fadeIn(500);
                });
                $(this).bind("mouseleave", function() {
                    var toolident = $(this).data("sadcow_toolident");
                    $("."+toolident).fadeOut(500, function() {
                        $("."+toolident).remove();
                    });
                });
            }
        });
    }
})( jQuery );


(function( $ ){
    $.fn.bestlength = function( options ) {

        var settings = {
            'height'   : 50,
            'accuracy' : 'auto',
            'failsafe' : 5000,
            'center' : true,
            'usetables': false
        };

        //center only words with non-inline elements (ie. don't float anything!)
        //usetables calculates only px-based padding (although you might not need padding if you use it)

        return this.each(function() {
            if ( options ) {
                $.extend( settings, options );
            }

            var eh;
            var ew = 1;

            $(this).css({"width":"auto","height":"auto"});
            if (settings['accuracy'] == 'auto') {
                var px = $(this).css("font-size");
                if (px.substr(px.length-2,2) != undefined && px.substr(px.length-2,2) == "px") {
                    px = px.substr(0, px.length-2);
                } else {
                    //can't tell
                    px = 30;
                }
                settings['accuracy'] = px;
            }

            var text = $(this).html();
            if (text == undefined || text.length < 1) {
                $(this).addClass("sadcow_no_content");
                return 0;
            }

            settings['accuracy'] = parseInt(settings['accuracy']);

            if (settings['accuracy'] < 1) {
                settings['accuracy'] = 1;
            }

            //make a copy
            var newcopy = $(this).clone();
            // newcopy.addClass("sadcowbestlengthmeasure").show().attr("style", newcopy.attr("style")+" filter:alpha(opacity=0);opacity: 0;-moz-opacity:0;");
            newcopy.addClass("sadcowbestlengthmeasure").show().css("word-wrap","break-word");
            newcopy.appendTo("body");

            $(".sadcowbestlengthmeasure").css({"width":settings['accuracy']+"px"});
            eh = $(".sadcowbestlengthmeasure").height();

            if (eh < settings['height']) {
                //can't do much with this
                $(".sadcowbestlengthmeasure").css({"width":"auto"});
            } else {
                var failsafe = 0;
                while (eh > settings['height']) {
                    eh = $(".sadcowbestlengthmeasure").height();
                    ew += settings['accuracy'];
                    $(".sadcowbestlengthmeasure").css({"width":ew+"px"});

                    failsafe ++;
                    if (failsafe > settings['failsafe']) {
                        $(".sadcowbestlengthmeasure").addClass("sadcow_bestlength_failsafe_hit");
                        break;
                    }
                }
            }

            $(".sadcowbestlengthmeasure").remove();

            ew += settings['accuracy'];

            $(this).css({"width":ew+"px","height":settings['height']+"px"});
            if (settings['center']) {
                if (settings['usetables']) {
                    var table_height = settings['height'];
                    var paddingtop = $(this).css('padding-top');
                    var paddingbottom = $(this).css('padding-top');
                    if (paddingtop != undefined && paddingtop.substr(paddingtop.length-2,2) == "px") {
                        paddingtop = paddingtop.substr(0, paddingtop.length-2);
                        table_height -= paddingtop;
                    }
                    if (paddingbottom != undefined && paddingbottom.substr(paddingbottom.length-2,2) == "px") {
                        paddingbottom = paddingbottom.substr(0, paddingbottom.length-2);
                        table_height -= paddingbottom;
                    }

                    $(this).html('<table style="width: '+ew+'px; height: '+table_height+'px; border-collapse:collapse; margin:0px; padding:0px;"><tr style="margin:0px; padding:0px;"><td align="center" valign="middle" style="text-align: center; vertical-align:middle; margin:0px; padding:0px">'+text+'</td></tr></table>');
                } else {
                    $(this).css({"display":"table-row"}).html('<div style="display:table-cell; vertical-align:middle;">'+text+'</div>');
                }
            }


        });
    }
})( jQuery );

(function( $ ){
    $.fn.sadcowcarousel = function( options ) {

        var settings = {
            'width'         : 931,
            'height'        : 100,
            'pathtocss'     : 'style/',
            'padding-vert'  : 3,
            'padding-hor'   : 3,
            'margin-vert'   : 3,
            'margin-hor'    : 3,
            'border'        : 1,
            'arrowwidth'    : 22,
            'speed'         : 300
        };
        return this.each(function() {
            if ( options ) {
                $.extend( settings, options );
            }

            //check it's not already been done
            if ($(this).data('sadcowcarouseled') == 1) {
                return;
            }

            $(this).data('sadcowcarouseled', 1)

            var items;
            var item_widths = [];
            var finalcode;
            var current_left = 0;
            var move = 0;
            var counter = 0;
            var top_move;

            items = $(this).html();

            var innerwidth = settings['width'] - (settings['arrowwidth'] * 2);
            var innerheight = settings['height'] - ((settings['padding-vert'] * 2) + (settings['margin-vert'] * 2) + (settings['border'] * 2));

            finalcode = '<div class="sadcowcarousel_border"></div>' +
                '<div class="sadcowcarousel_overall_container" style="width: '+settings['width']+'px;">' +
                    '<div class="sadcowcarousel_control sadcowcarousel_go_right" style="width: '+settings['arrowwidth']+'px;"></div>' +
                    '<div class="sadcowcarousel_control sadcowcarousel_go_left" style="width: '+settings['arrowwidth']+'px;"></div>' +
                        '<div class="sadcowcarousel_content_outer" style="width: '+innerwidth+'px; height: '+settings['height']+'px;">' +
                            '<div class="sadcowcarousel_content" style="width: 9000px">';
                                finalcode += items; finalcode += '' +
                            '</div>' +
                        '</div>' +
                    '<div class="clear"></div>' +
                '</div>' +
            '<div class="sadcowcarousel_border"></div>';

            $(this).html(finalcode);

            $(".sadcowcarousel_content li").bestlength({
                'height'   : innerheight,
                'center' : false
            });

            $(".sadcowcarousel_content li").css({
                "padding-top":settings['padding-vert']+'px',
                "padding-bottom":settings['padding-vert']+'px',
                "padding-left":settings['padding-hor']+'px',
                "padding-right":settings['padding-hor']+'px',
                "margin-top":settings['margin-vert']+'px',
                "margin-bottom":settings['margin-vert']+'px',
                "margin-left":settings['margin-hor']+'px',
                "margin-right":settings['margin-hor']+'px',
                "border-width":settings['border']+'px'
            });

            $(".sadcowcarousel_control").css("height",settings['height']+"px");

            $(".sadcowcarousel_content li").each(function() {
                item_widths[counter] = $(this).width() + (settings['padding-hor'] * 2) + (settings['margin-hor'] * 2) + (settings['border'] * 2);
                counter ++;
            });

            top_move = counter - 1;

            $(".sadcowcarousel_go_right").click(function() {
                if (move == top_move) {
                    return false;
                }
                current_left -= item_widths[move];
                move ++;
                $(".sadcowcarousel_content").animate({"margin-left":current_left+"px"}, settings['speed']);
            });

            $(".sadcowcarousel_go_left").click(function() {
                if (move == 0) {
                    return false;
                }
                move --;
                current_left += item_widths[move];
                $(".sadcowcarousel_content").animate({"margin-left":current_left+"px"}, settings['speed']);
            });

        });
    }
})( jQuery );


jQuery.beautyOfCode={settings:{autoLoad:true,baseUrl:'http://alexgorbatchev.com.s3.amazonaws.com/pub/sh/2.1.364/',scripts:'scripts/',styles:'styles/',theme:'Default',brushes:['Xml','JScript','CSharp','Plain'],config:{},defaults:{},ready:function(){jQuery.beautyOfCode.beautifyAll();}},init:function(settings){settings=jQuery.extend({},jQuery.beautyOfCode.settings,settings);if(!settings.config.clipboardSwf)
settings.config.clipboardSwf=settings.baseUrl+settings.scripts+'clipboard.swf';jQuery(document).ready(function(){if(!settings.autoLoad){settings.ready();}
else{jQuery.beautyOfCode.utils.loadCss('http://www.sadcow.co.uk/style/shCore.css');
//jQuery.beautyOfCode.utils.loadCss(settings.baseUrl+settings.styles+'shTheme'+settings.theme+'.css','shTheme');
var scripts=new Array();scripts.push(settings.baseUrl+settings.scripts+'shCore.js');jQuery.each(settings.brushes,function(i,item){scripts.push(settings.baseUrl+settings.scripts+'shBrush'+item+".js");});jQuery.beautyOfCode.utils.loadAllScripts(scripts,function(){if(settings&&settings.config)
jQuery.extend(SyntaxHighlighter.config,settings.config);if(settings&&settings.defaults)
jQuery.extend(SyntaxHighlighter.defaults,settings.defaults);settings.ready();});}});},beautifyAll:function(){jQuery("pre.code:has(code[class]),code.code").beautifyCode();},utils:{loadScript:function(url,complete){jQuery.ajax({url:url,complete:function(){complete();},type:'GET',dataType:'script',cache:true});},loadAllScripts:function(urls,complete){if(!urls||urls.length==0)
{complete();return;}
var first=urls[0];jQuery.beautyOfCode.utils.loadScript(first,function(){jQuery.beautyOfCode.utils.loadAllScripts(urls.slice(1,urls.length),complete);});},loadCss:function(url,id){var headNode=jQuery("head")[0];if(url&&headNode)
{var styleNode=document.createElement('link');styleNode.setAttribute('rel','stylesheet');styleNode.setAttribute('href',url);if(id)styleNode.id=id;headNode.appendChild(styleNode);}},addCss:function(css,id){var headNode=jQuery("head")[0];if(css&&headNode)
{var styleNode=document.createElement('style');styleNode.setAttribute('type','text/css');if(id)styleNode.id=id;if(styleNode.styleSheet){styleNode.styleSheet.cssText=css;}
else{jQuery(styleNode).text(css);}
headNode.appendChild(styleNode);}},addCssForBrush:function(brush,highlighter){if(brush.isCssInitialized)
return;jQuery.beautyOfCode.utils.addCss(highlighter.Style);brush.isCssInitialized=true;},parseParams:function(params){var trimmed=jQuery.map(params,jQuery.trim);var paramObject={};var getOptionValue=function(name,list){var regex=new RegExp('^'+name+'\\[([^\\]]+)\\]$','gi');var matches=null;for(var i=0;i<list.length;i++)
if((matches=regex.exec(list[i]))!=null)
return matches[1];return null;}
var handleValue=function(flag){var flagValue=getOptionValue('boc-'+flag,trimmed);if(flagValue)paramObject[flag]=flagValue;};handleValue('class-name');handleValue('first-line');handleValue('tab-size');var highlight=getOptionValue('boc-highlight',trimmed);if(highlight)paramObject['highlight']=jQuery.map(highlight.split(','),jQuery.trim);var handleFlag=function(flag){if(jQuery.inArray('boc-'+flag,trimmed)!=-1)
paramObject[flag]=true;else if(jQuery.inArray('boc-no-'+flag,trimmed)!=-1)
paramObject[flag]=false;};handleFlag('smart-tabs');handleFlag('ruler');handleFlag('gutter');handleFlag('toolbar');handleFlag('collapse');handleFlag('auto-links');handleFlag('light');handleFlag('wrap-lines');handleFlag('html-script');return paramObject;}}};jQuery.fn.beautifyCode=function(brush,params){var saveBrush=brush;var saveParams=params;this.each(function(i,item){var $item=jQuery(item);var $code=$item.is('code')?$item:$item.children("code");var code=$code[0];var classItems=code.className.replace(/.+?(brush:|language-)/,'$1').replace('language-','').split(" ");var brush=saveBrush?saveBrush:classItems[0];var elementParams=jQuery.beautyOfCode.utils.parseParams(classItems);var params=jQuery.extend({},SyntaxHighlighter.defaults,saveParams,elementParams);if(params['html-script']=='true')
{highlighter=new SyntaxHighlighter.HtmlScript(brush);}
else
{var brush=SyntaxHighlighter.utils.findBrush(brush);if(brush)
highlighter=new brush();else
return;}
jQuery.beautyOfCode.utils.addCssForBrush(brush,highlighter);if($item.is("pre")&&($code=$item.children("code")))
$item.text($code.text());highlighter.highlight($item.html(),params);highlighter.source=item;$item.replaceWith(highlighter.div);});};






/*
 * jQuery history plugin
 * 
 * The MIT License
 * 
 * Copyright (c) 2006-2009 Taku Sano (Mikage Sawatari)
 * Copyright (c) 2010 Takayuki Miwa
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

(function($) {
    var locationWrapper = {
        put: function(hash, win) {
            (win || window).location.hash = this.encoder(hash);
        },
        get: function(win) {
            var hash = ((win || window).location.hash).replace(/^#/, '');
            try {
                return $.browser.mozilla ? hash : decodeURIComponent(hash);
            }
            catch (error) {
                return hash;
            }
        },
        encoder: encodeURIComponent
    };

    var iframeWrapper = {
        id: "__jQuery_history",
        init: function() {
            var html = '<iframe id="'+ this.id +'" style="display:none" src="javascript:false;" />';
            $("body").prepend(html);
            return this;
        },
        _document: function() {
            return $("#"+ this.id)[0].contentWindow.document;
        },
        put: function(hash) {
            var doc = this._document();
            doc.open();
            doc.close();
            locationWrapper.put(hash, doc);
        },
        get: function() {
            return locationWrapper.get(this._document());
        }
    };

    function initObjects(options) {
        options = $.extend({
                unescape: false
            }, options || {});

        locationWrapper.encoder = encoder(options.unescape);

        function encoder(unescape_) {
            if(unescape_ === true) {
                return function(hash){ return hash; };
            }
            if(typeof unescape_ == "string" &&
               (unescape_ = partialDecoder(unescape_.split("")))
               || typeof unescape_ == "function") {
                return function(hash) { return unescape_(encodeURIComponent(hash)); };
            }
            return encodeURIComponent;
        }

        function partialDecoder(chars) {
            var re = new RegExp($.map(chars, encodeURIComponent).join("|"), "ig");
            return function(enc) { return enc.replace(re, decodeURIComponent); };
        }
    }

    var implementations = {};

    implementations.base = {
        callback: undefined,
        type: undefined,

        check: function() {},
        load:  function(hash) {},
        init:  function(callback, options) {
            initObjects(options);
            self.callback = callback;
            self._options = options;
            self._init();
        },

        _init: function() {},
        _options: {}
    };

    implementations.timer = {
        _appState: undefined,
        _init: function() {
            var current_hash = locationWrapper.get();
            self._appState = current_hash;
            self.callback(current_hash);
            setInterval(self.check, 100);
        },
        check: function() {
            var current_hash = locationWrapper.get();
            if(current_hash != self._appState) {
                self._appState = current_hash;
                self.callback(current_hash);
            }
        },
        load: function(hash) {
            if(hash != self._appState) {
                locationWrapper.put(hash);
                self._appState = hash;
                self.callback(hash);
            }
        }
    };

    implementations.iframeTimer = {
        _appState: undefined,
        _init: function() {
            var current_hash = locationWrapper.get();
            self._appState = current_hash;
            iframeWrapper.init().put(current_hash);
            self.callback(current_hash);
            setInterval(self.check, 100);
        },
        check: function() {
            var iframe_hash = iframeWrapper.get(),
                location_hash = locationWrapper.get();

            if (location_hash != iframe_hash) {
                if (location_hash == self._appState) {    // user used Back or Forward button
                    self._appState = iframe_hash;
                    locationWrapper.put(iframe_hash);
                    self.callback(iframe_hash); 
                } else {                              // user loaded new bookmark
                    self._appState = location_hash;  
                    iframeWrapper.put(location_hash);
                    self.callback(location_hash);
                }
            }
        },
        load: function(hash) {
            if(hash != self._appState) {
                locationWrapper.put(hash);
                iframeWrapper.put(hash);
                self._appState = hash;
                self.callback(hash);
            }
        }
    };

    implementations.hashchangeEvent = {
        _init: function() {
            self.callback(locationWrapper.get());
            $(window).bind('hashchange', self.check);
        },
        check: function() {
            self.callback(locationWrapper.get());
        },
        load: function(hash) {
            locationWrapper.put(hash);
        }
    };

    var self = $.extend({}, implementations.base);

    if($.browser.msie && ($.browser.version < 8 || document.documentMode < 8)) {
        self.type = 'iframeTimer';
    } else if("onhashchange" in window) {
        self.type = 'hashchangeEvent';
    } else {
        self.type = 'timer';
    }

    $.extend(self, implementations[self.type]);
    $.history = self;
})(jQuery);
