
//-----------------------------------------------------------------------------
// console-fallback.js - 16325
// Protect against any console.log() calls if console unavailable
//-----------------------------------------------------------------------------
if (typeof(console) === 'undefined')
{
    var console = {};

    console.log = console.error = console.info = console.debug = console.warn
        = console.trace = console.dir = console.dirxml = console.group
        = console.groupEnd = console.time = console.timeEnd = console.assert
        = console.profile = function() {};
}

//-----------------------------------------------------------------------------
// global.js - 11350
// General functions to apply on all pages
//-----------------------------------------------------------------------------
$(function() {
    general_init();
    load_scripts();
    init_google_tracking();
    setup_donate_faqs();
    text_size_widget();
    facebook_like_inject();
    nav_highlight();
    track_files();
    track_promos();
    init_quick_donate();
    quick_donate_other();
    auto_gallery();
    init_photo_galleries();
    dynamic_gallery();
    init_maps();
    init_regional_maps();
    load_how_people_are_helping();
    init_scrollers();
    init_slideshow_tickers();
    friendship_funday_ladder();
    little_jack_game();
    video_popups();
    moodboard_popups();
    init_carousels();
    init_blog_feeds();
    init_flash_videos();
    init_postcode_anywhere();
    carousel_popup();
    flash_countdown();
    healthworkers_progress();
    init_calendars();
});

function general_init()
{
    $('.showmejs').show();
    $('.hide-by-js').hide();


    // Enable input elements with a 'default-text' class to hide that value when entered
    // and restore it if left unchanged

    $('input.default-text')
        .live('focus', function(ev) {
            ev.target.value = ev.target.defaultValue == ev.target.value ? "" : ev.target.value;
        })
        .live('blur', function(ev) {
            ev.target.value = ev.target.value ? ev.target.value : ev.target.defaultValue;
        });

    $('.clearonsubmit').each(function() {
        var input = this;

        $(this).parents('form').submit(function() {
            if (input.defaultValue == input.value)
                input.value = '';
        });
    });
};


// Track clicks on promo box links via Google Analytics.

function promo_tracking(id, id2)
{
    $('#' + id + ' h3 a').click(function() {
        var el = document.getElementById(id);
        var n = $(el).parent().find('> div.promo').index(el) + 1;
        var label = "/promo" + n + (id2 ? "/" + id2 : "") + "/" + id;

        _gaq.push(['_trackEvent', "Click", "Promo", n + (id2 ? "/" + id2 : "") + "/" + id]);
    });
}
 


//-----------------------------------------------------------------------------
// clog - 10361
// Log debug to firebug console, if it's available
//-----------------------------------------------------------------------------
function clog(str)
{
    if (window.console)
    {
        console.log(str);
    }
}

//-----------------------------------------------------------------------------
// filter - 10699
// Remove each element from an array depending on result of callback function, func.
//-----------------------------------------------------------------------------
function filter(arr, func) {
    for (i = arr.length; i >= 0; i--) {
        if (func(arr[i])) { arr.splice(i, 1); }
    }
}

//-----------------------------------------------------------------------------
// fromISODate - 10380
// Convert a (short) ISO date string into a javascript Date object.
//-----------------------------------------------------------------------------
function fromISODate(date)
{
    var year   = date.substr(0, 4);
    var month  = parseInt(unpad(date.substr(5, 2))) - 1;
    var day    = date.substr(8, 2);

    return new Date(year, month, day);
}

//-----------------------------------------------------------------------------
// pad - 10369
// Add leading zero to numbers < 10
//-----------------------------------------------------------------------------
function pad(n) { return n < 10 ? '0' + n : n; }

//-----------------------------------------------------------------------------
// toISODate - 10379
// Convert a javascript Date object into a (short) ISO date string
//-----------------------------------------------------------------------------
function toISODate(date) {
    return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate());
}

//-----------------------------------------------------------------------------
// trim - 16259
//-----------------------------------------------------------------------------
function trim(str, chr)
{
    if (str[0] == chr)
        str = str.substring(1);
 
    if (str[str.length - 1] == chr)
        str = str.substring(0, str.length - 1);
 
    return str;
}

//-----------------------------------------------------------------------------
// unpad - 10370
// Remove leading zero, if present
//-----------------------------------------------------------------------------
function unpad(n) { return n.substr(0, 1) === '0' ? n.substr(1) : n; }



//-----------------------------------------------------------------------------
// $.cookie() - 11121
// jquery cookie plugin - from https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js
//-----------------------------------------------------------------------------
/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

//-----------------------------------------------------------------------------
// $.getUrlVars() - 10358
// Add a function to jQuery to extract the values of URL parameters.
//-----------------------------------------------------------------------------
$.extend({
    getUrlVars: function() {
        var vars = [], hash;
        var href = window.location.href;
        var hashes = href.slice(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];
    }
});

//-----------------------------------------------------------------------------
// jquery.prettyTooltip.js - 11293
// 'Upgrade' tooltips from the browser's default to a CSS-styled tooltip with fade in/out animation. The tooltip text is grabbed from the 'title' attribute of each link (which is normally displayed as a tooltip).
//-----------------------------------------------------------------------------
(function($) {
    $.fn.extend({
        prettyTooltip: function() {
            return this.each(function() {
                $(this).hover(
                    function(ev) {
                        var $this = $(this);

                        var title = $this.attr('title');

                        $this.data('title', title);

                        $this.attr('title', '');

                        $pos = $this.offset();
                        $dims = { width: $this.outerWidth(), height: $this.outerHeight() };

                        $('<span class="tooltip">' + title.replace(/ /g, '&nbsp;') + '</span>').css({
                            top: $pos.top - 30 + 'px',
                            left: $pos.left + ($dims.width / 2) + 'px'
                        }).insertAfter(this).hide().fadeIn('slow');
                    },

                    function() {
                        $(this).next('span.tooltip').fadeOut('fast', function() {
                            $(this).remove();
                        });

                        $(this).attr('title', $(this).data('title'));
                    }
                );
            });
        }
    });
})(jQuery);

//-----------------------------------------------------------------------------
// jquery.timers-1.2.js - 11654
//-----------------------------------------------------------------------------
/**
 * jQuery.timers - Timer abstractions for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/10/16
 *
 * @author Blair Mitchelmore
 * @version 1.2
 *
 **/
jQuery.fn.extend({
 everyTime: function(interval, label, fn, times) {
  return this.each(function() {
   jQuery.timer.add(this, interval, label, fn, times);
  });
 },
 oneTime: function(interval, label, fn) {
  return this.each(function() {
   jQuery.timer.add(this, interval, label, fn, 1);
  });
 },
 stopTime: function(label, fn) {
  return this.each(function() {
   jQuery.timer.remove(this, label, fn);
  });
 }
});
jQuery.extend({
 timer: {
  global: [],
  guid: 1,
  dataKey: "jQuery.timer",
  regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
  powers: {
   // Yeah this is major overkill...
   'ms': 1,
   'cs': 10,
   'ds': 100,
   's': 1000,
   'das': 10000,
   'hs': 100000,
   'ks': 1000000
  },
  timeParse: function(value) {
   if (value == undefined || value == null)
    return null;
   var result = this.regex.exec(jQuery.trim(value.toString()));
   if (result[2]) {
    var num = parseFloat(result[1]);
    var mult = this.powers[result[2]] || 1;
    return num * mult;
   } else {
    return value;
   }
  },
  add: function(element, interval, label, fn, times) {
   var counter = 0;
   
   if (jQuery.isFunction(label)) {
    if (!times) 
     times = fn;
    fn = label;
    label = interval;
   }
   
   interval = jQuery.timer.timeParse(interval);
   if (typeof interval != 'number' || isNaN(interval) || interval < 0)
    return;
   if (typeof times != 'number' || isNaN(times) || times < 0) 
    times = 0;
   
   times = times || 0;
   
   var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
   
   if (!timers[label])
    timers[label] = {};
   
   fn.timerID = fn.timerID || this.guid++;
   
   var handler = function() {
    if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
     jQuery.timer.remove(element, label, fn);
   };
   
   handler.timerID = fn.timerID;
   
   if (!timers[label][fn.timerID])
    timers[label][fn.timerID] = window.setInterval(handler,interval);
   
   this.global.push( element );
   
  },
  remove: function(element, label, fn) {
   var timers = jQuery.data(element, this.dataKey), ret;
   
   if ( timers ) {
    
    if (!label) {
     for ( label in timers )
      this.remove(element, label, fn);
    } else if ( timers[label] ) {
     if ( fn ) {
      if ( fn.timerID ) {
       window.clearInterval(timers[label][fn.timerID]);
       delete timers[label][fn.timerID];
      }
     } else {
      for ( var fn in timers[label] ) {
       window.clearInterval(timers[label][fn]);
       delete timers[label][fn];
      }
     }
     
     for ( ret in timers[label] ) break;
     if ( !ret ) {
      ret = null;
      delete timers[label];
     }
    }
    
    for ( ret in timers ) break;
    if ( !ret ) 
     jQuery.removeData(element, this.dataKey);
   }
  }
 }
});
jQuery(window).bind("unload", function() {
 jQuery.each(jQuery.timer.global, function(index, item) {
  jQuery.timer.remove(item);
 });
});

//-----------------------------------------------------------------------------
// jquery.swfobject.js - 13589
//-----------------------------------------------------------------------------
// jQuery SWFObject v1.1.1 MIT/GPL @jon_neal
// http://jquery.thewikies.com/swfobject
(function(f,h,i){function k(a,c){var b=(a[0]||0)-(c[0]||0);return b>0||!b&&a.length>0&&k(a.slice(1),c.slice(1))}function l(a){if(typeof a!=g)return a;var c=[],b="";for(var d in a){b=typeof a[d]==g?l(a[d]):[d,m?encodeURI(a[d]):a[d]].join("=");c.push(b)}return c.join("&")}function n(a){var c=[];for(var b in a)a[b]&&c.push([b,'="',a[b],'"'].join(""));return c.join(" ")}function o(a){var c=[];for(var b in a)c.push(['<param name="',b,'" value="',l(a[b]),'" />'].join(""));return c.join("")}var g="object",m=true;try{var j=i.description||function(){return(new i("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version")}()}catch(p){j="Unavailable"}var e=j.match(/\d+/g)||[0];f[h]={available:e[0]>0,activeX:i&&!i.name,version:{original:j,array:e,string:e.join("."),major:parseInt(e[0],10)||0,minor:parseInt(e[1],10)||0,release:parseInt(e[2],10)||0},hasVersion:function(a){a=/string|number/.test(typeof a)?a.toString().split("."):/object/.test(typeof a)?[a.major,a.minor]:a||[0,0];return k(e,a)},encodeParams:true,expressInstall:"expressInstall.swf",expressInstallIsActive:false,create:function(a){if(!a.swf||this.expressInstallIsActive||!this.available&&!a.hasVersionFail)return false;if(!this.hasVersion(a.hasVersion||1)){this.expressInstallIsActive=true;if(typeof a.hasVersionFail=="function")if(!a.hasVersionFail.apply(a))return false;a={swf:a.expressInstall||this.expressInstall,height:137,width:214,flashvars:{MMredirectURL:location.href,MMplayerType:this.activeX?"ActiveX":"PlugIn",MMdoctitle:document.title.slice(0,47)+" - Flash Player Installation"}}}attrs={data:a.swf,type:"application/x-shockwave-flash",id:a.id||"flash_"+Math.floor(Math.random()*999999999),width:a.width||320,height:a.height||180,style:a.style||""};m=typeof a.useEncode!=="undefined"?a.useEncode:this.encodeParams;a.movie=a.swf;a.wmode=a.wmode||"opaque";delete a.fallback;delete a.hasVersion;delete a.hasVersionFail;delete a.height;delete a.id;delete a.swf;delete a.useEncode;delete a.width;var c=document.createElement("div");c.innerHTML=["<object ",n(attrs),">",o(a),"</object>"].join("");return c.firstChild}};f.fn[h]=function(a){var c=this.find(g).andSelf().filter(g);/string|object/.test(typeof a)&&this.each(function(){var b=f(this),d;a=typeof a==g?a:{swf:a};a.fallback=this;if(d=f[h].create(a)){b.children().remove();b.html(d)}});typeof a=="function"&&c.each(function(){var b=this;b.jsInteractionTimeoutMs=b.jsInteractionTimeoutMs||0;if(b.jsInteractionTimeoutMs<660)b.clientWidth||b.clientHeight?a.call(b):setTimeout(function(){f(b)[h](a)},b.jsInteractionTimeoutMs+66)});return c}})(jQuery,"flash",navigator.plugins["Shockwave Flash"]||window.ActiveXObject);

//-----------------------------------------------------------------------------
// jquery.fancybox.js - 12749
//-----------------------------------------------------------------------------
/*
 * FancyBox - jQuery Plugin
 * Simple and fancy lightbox alternative
 *
 * Examples and documentation at: http://fancybox.net
 * 
 * Copyright (c) 2008 - 2010 Janis Skarnelis
 *
 * Version: 1.3.1 (05/03/2010)
 * Requires: jQuery v1.3+
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
(function($) {
 var tmp, loading, overlay, wrap, outer, inner, close, nav_left, nav_right,
  selectedIndex = 0, selectedOpts = {}, selectedArray = [], currentIndex = 0, currentOpts = {}, currentArray = [],
  ajaxLoader = null, imgPreloader = new Image(), imgRegExp = /\.(jpg|gif|png|bmp|jpeg)(.*)?$/i, swfRegExp = /[^\.]\.(swf)\s*$/i,
  loadingTimer, loadingFrame = 1,
  start_pos, final_pos, busy = false, shadow = 20, fx = $.extend($('<div/>')[0], { prop: 0 }), titleh = 0, 
  isIE6 = !$.support.opacity && !window.XMLHttpRequest,
  /*
   * Private methods 
   */
  fancybox_abort = function() {
   loading.hide();
   imgPreloader.onerror = imgPreloader.onload = null;
   if (ajaxLoader) {
    ajaxLoader.abort();
   }
   tmp.empty();
  },
  fancybox_error = function() {
   $.fancybox('<p id="fancybox_error">The requested content cannot be loaded.<br />Please try again later.</p>', {
    'scrolling'  : 'no',
    'padding'  : 20,
    'transitionIn' : 'none',
    'transitionOut' : 'none'
   });
  },
  fancybox_get_viewport = function() {
   return [ $(window).width(), $(window).height(), $(document).scrollLeft(), $(document).scrollTop() ];
  },
  fancybox_get_zoom_to = function () {
   var view = fancybox_get_viewport(),
    to  = {},
    margin = currentOpts.margin,
    resize = currentOpts.autoScale,
    horizontal_space = (shadow + margin) * 2,
    vertical_space  = (shadow + margin) * 2,
    double_padding  = (currentOpts.padding * 2),
    
    ratio;
   if (currentOpts.width.toString().indexOf('%') > -1) {
    to.width = ((view[0] * parseFloat(currentOpts.width)) / 100) - (shadow * 2) ;
    resize = false;
   } else {
    to.width = currentOpts.width + double_padding;
   }
   if (currentOpts.height.toString().indexOf('%') > -1) {
    to.height = ((view[1] * parseFloat(currentOpts.height)) / 100) - (shadow * 2);
    resize = false;
   } else {
    to.height = currentOpts.height + double_padding;
   }
   if (resize && (to.width > (view[0] - horizontal_space) || to.height > (view[1] - vertical_space))) {
    if (selectedOpts.type == 'image' || selectedOpts.type == 'swf') {
     horizontal_space += double_padding;
     vertical_space  += double_padding;
     ratio = Math.min(Math.min( view[0] - horizontal_space, currentOpts.width) / currentOpts.width, Math.min( view[1] - vertical_space, currentOpts.height) / currentOpts.height);
     to.width = Math.round(ratio * (to.width - double_padding)) + double_padding;
     to.height = Math.round(ratio * (to.height - double_padding)) + double_padding;
    } else {
     to.width = Math.min(to.width, (view[0] - horizontal_space));
     to.height = Math.min(to.height, (view[1] - vertical_space));
    }
   }
   to.top = view[3] + ((view[1] - (to.height + (shadow * 2 ))) * 0.5);
   to.left = view[2] + ((view[0] - (to.width + (shadow * 2 ))) * 0.5);
   if (currentOpts.autoScale === false) {
    to.top = Math.max(view[3] + margin, to.top);
    to.left = Math.max(view[2] + margin, to.left);
   }
   return to;
  },
  fancybox_format_title = function(title) {
   if (title && title.length) {
    switch (currentOpts.titlePosition) {
     case 'inside':
      return title;
     case 'over':
      return '<span id="fancybox-title-over">' + title + '</span>';
     default:
      return '<span id="fancybox-title-wrap"><span id="fancybox-title-left"></span><span id="fancybox-title-main">' + title + '</span><span id="fancybox-title-right"></span></span>';
    }
   }
   return false;
  },
  fancybox_process_title = function() {
   var title = currentOpts.title,
    width = final_pos.width - (currentOpts.padding * 2),
    titlec = 'fancybox-title-' + currentOpts.titlePosition;
    
   $('#fancybox-title').remove();
   titleh = 0;
   if (currentOpts.titleShow === false) {
    return;
   }
   title = $.isFunction(currentOpts.titleFormat) ? currentOpts.titleFormat(title, currentArray, currentIndex, currentOpts) : fancybox_format_title(title);
   if (!title || title === '') {
    return;
   }
   $('<div id="fancybox-title" class="' + titlec + '" />').css({
    'width'   : width,
    'paddingLeft' : currentOpts.padding,
    'paddingRight' : currentOpts.padding
   }).html(title).appendTo('body');
   switch (currentOpts.titlePosition) {
    case 'inside':
     titleh = $("#fancybox-title").outerHeight(true) - currentOpts.padding;
     final_pos.height += titleh;
    break;
    case 'over':
     $('#fancybox-title').css('bottom', currentOpts.padding);
    break;
    default:
     $('#fancybox-title').css('bottom', $("#fancybox-title").outerHeight(true) * -1);
    break;
   }
   $('#fancybox-title').appendTo( outer ).hide();
  },
  fancybox_set_navigation = function() {
   $(document).unbind('keydown.fb').bind('keydown.fb', function(e) {
    if (e.keyCode == 27 && currentOpts.enableEscapeButton) {
     e.preventDefault();
     $.fancybox.close();
    } else if (e.keyCode == 37) {
     e.preventDefault();
     $.fancybox.prev();
    } else if (e.keyCode == 39) {
     e.preventDefault();
     $.fancybox.next();
    }
   });
   if ($.fn.mousewheel) {
    wrap.unbind('mousewheel.fb');
    if (currentArray.length > 1) {
     wrap.bind('mousewheel.fb', function(e, delta) {
      e.preventDefault();
      if (busy || delta === 0) {
       return;
      }
      if (delta > 0) {
       $.fancybox.prev();
      } else {
       $.fancybox.next();
      }
     });
    }
   }
   if (!currentOpts.showNavArrows) { return; }
   if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex !== 0) {
    nav_left.show();
   }
   if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex != (currentArray.length -1)) {
    nav_right.show();
   }
  },
  fancybox_preload_images = function() {
   var href, 
    objNext;
    
   if ((currentArray.length -1) > currentIndex) {
    href = currentArray[ currentIndex + 1 ].href;
    if (typeof href !== 'undefined' && href.match(imgRegExp)) {
     objNext = new Image();
     objNext.src = href;
    }
   }
   if (currentIndex > 0) {
    href = currentArray[ currentIndex - 1 ].href;
    if (typeof href !== 'undefined' && href.match(imgRegExp)) {
     objNext = new Image();
     objNext.src = href;
    }
   }
  },
  _finish = function () {
   inner.css('overflow', (currentOpts.scrolling == 'auto' ? (currentOpts.type == 'image' || currentOpts.type == 'iframe' || currentOpts.type == 'swf' ? 'hidden' : 'auto') : (currentOpts.scrolling == 'yes' ? 'auto' : 'visible')));
   if (!$.support.opacity) {
    inner.get(0).style.removeAttribute('filter');
    wrap.get(0).style.removeAttribute('filter');
   }
   $('#fancybox-title').show();
   if (currentOpts.hideOnContentClick) {
    inner.one('click', $.fancybox.close);
   }
   if (currentOpts.hideOnOverlayClick) {
    overlay.one('click', $.fancybox.close);
   }
   if (currentOpts.showCloseButton) {
    close.show();
   }
   fancybox_set_navigation();
   $(window).bind("resize.fb", $.fancybox.center);
   if (currentOpts.centerOnScroll) {
    $(window).bind("scroll.fb", $.fancybox.center);
   } else {
    $(window).unbind("scroll.fb");
   }
   if ($.isFunction(currentOpts.onComplete)) {
    currentOpts.onComplete(currentArray, currentIndex, currentOpts);
   }
   busy = false;
   fancybox_preload_images();
  },
  fancybox_draw = function(pos) {
   var width = Math.round(start_pos.width + (final_pos.width - start_pos.width) * pos),
    height = Math.round(start_pos.height + (final_pos.height - start_pos.height) * pos),
    top  = Math.round(start_pos.top + (final_pos.top - start_pos.top) * pos),
    left = Math.round(start_pos.left + (final_pos.left - start_pos.left) * pos);
   wrap.css({
    'width'  : width  + 'px',
    'height' : height + 'px',
    'top'  : top  + 'px',
    'left'  : left  + 'px'
   });
   width = Math.max(width - currentOpts.padding * 2, 0);
   height = Math.max(height - (currentOpts.padding * 2 + (titleh * pos)), 0);
   inner.css({
    'width'  : width  + 'px',
    'height' : height + 'px'
   });
   if (typeof final_pos.opacity !== 'undefined') {
    wrap.css('opacity', (pos < 0.5 ? 0.5 : pos));
   }
  },
  fancybox_get_obj_pos = function(obj) {
   var pos  = obj.offset();
   pos.top  += parseFloat( obj.css('paddingTop') ) || 0;
   pos.left += parseFloat( obj.css('paddingLeft') ) || 0;
   pos.top  += parseFloat( obj.css('border-top-width') ) || 0;
   pos.left += parseFloat( obj.css('border-left-width') ) || 0;
   pos.width = obj.width();
   pos.height = obj.height();
   return pos;
  },
  fancybox_get_zoom_from = function() {
   var orig = selectedOpts.orig ? $(selectedOpts.orig) : false,
    from = {},
    pos,
    view;
   if (orig && orig.length) {
    pos = fancybox_get_obj_pos(orig);
    from = {
     width : (pos.width + (currentOpts.padding * 2)),
     height : (pos.height + (currentOpts.padding * 2)),
     top  : (pos.top  - currentOpts.padding - shadow),
     left : (pos.left  - currentOpts.padding - shadow)
    };
    
   } else {
    view = fancybox_get_viewport();
    from = {
     width : 1,
     height : 1,
     top  : view[3] + view[1] * 0.5,
     left : view[2] + view[0] * 0.5
    };
   }
   return from;
  },
  fancybox_show = function() {
   loading.hide();
   if (wrap.is(":visible") && $.isFunction(currentOpts.onCleanup)) {
    if (currentOpts.onCleanup(currentArray, currentIndex, currentOpts) === false) {
     $.event.trigger('fancybox-cancel');
     busy = false;
     return;
    }
   }
   currentArray = selectedArray;
   currentIndex = selectedIndex;
   currentOpts  = selectedOpts;
   inner.get(0).scrollTop = 0;
   inner.get(0).scrollLeft = 0;
   if (currentOpts.overlayShow) {
    if (isIE6) {
     $('select:not(#fancybox-tmp select)').filter(function() {
      return this.style.visibility !== 'hidden';
     }).css({'visibility':'hidden'}).one('fancybox-cleanup', function() {
      this.style.visibility = 'inherit';
     });
    }
    overlay.css({
     'background-color' : currentOpts.overlayColor,
     'opacity'   : currentOpts.overlayOpacity
    }).unbind().show();
   }
   final_pos = fancybox_get_zoom_to();
   fancybox_process_title();
   if (wrap.is(":visible")) {
    $( close.add( nav_left ).add( nav_right ) ).hide();
    var pos = wrap.position(),
     equal;
    start_pos = {
     top  : pos.top ,
     left : pos.left,
     width : wrap.width(),
     height : wrap.height()
    };
    equal = (start_pos.width == final_pos.width && start_pos.height == final_pos.height);
    inner.fadeOut(currentOpts.changeFade, function() {
     var finish_resizing = function() {
      inner.html( tmp.contents() ).fadeIn(currentOpts.changeFade, _finish);
     };
     
     $.event.trigger('fancybox-change');
     inner.empty().css('overflow', 'hidden');
     if (equal) {
      inner.css({
       top   : currentOpts.padding,
       left  : currentOpts.padding,
       width  : Math.max(final_pos.width - (currentOpts.padding * 2), 1),
       height  : Math.max(final_pos.height - (currentOpts.padding * 2) - titleh, 1)
      });
      
      finish_resizing();
     } else {
      inner.css({
       top   : currentOpts.padding,
       left  : currentOpts.padding,
       width  : Math.max(start_pos.width - (currentOpts.padding * 2), 1),
       height  : Math.max(start_pos.height - (currentOpts.padding * 2), 1)
      });
      
      fx.prop = 0;
      $(fx).animate({ prop: 1 }, {
        duration : currentOpts.changeSpeed,
        easing  : currentOpts.easingChange,
        step  : fancybox_draw,
        complete : finish_resizing
      });
     }
    });
    return;
   }
   wrap.css('opacity', 1);
   if (currentOpts.transitionIn == 'elastic') {
    start_pos = fancybox_get_zoom_from();
    inner.css({
      top   : currentOpts.padding,
      left  : currentOpts.padding,
      width  : Math.max(start_pos.width - (currentOpts.padding * 2), 1),
      height  : Math.max(start_pos.height - (currentOpts.padding * 2), 1)
     })
     .html( tmp.contents() );
    wrap.css(start_pos).show();
    if (currentOpts.opacity) {
     final_pos.opacity = 0;
    }
    fx.prop = 0;
    $(fx).animate({ prop: 1 }, {
      duration : currentOpts.speedIn,
      easing  : currentOpts.easingIn,
      step  : fancybox_draw,
      complete : _finish
    });
   } else {
    inner.css({
      top   : currentOpts.padding,
      left  : currentOpts.padding,
      width  : Math.max(final_pos.width - (currentOpts.padding * 2), 1),
      height  : Math.max(final_pos.height - (currentOpts.padding * 2) - titleh, 1)
     })
     .html( tmp.contents() );
    wrap.css( final_pos ).fadeIn( currentOpts.transitionIn == 'none' ? 0 : currentOpts.speedIn, _finish );
   }
  },
  fancybox_process_inline = function() {
   tmp.width( selectedOpts.width );
   tmp.height( selectedOpts.height );
   if (selectedOpts.width == 'auto') {
    selectedOpts.width = tmp.width();
   }
   if (selectedOpts.height == 'auto') {
    selectedOpts.height = tmp.height();
   }
   fancybox_show();
  },
  
  fancybox_process_image = function() {
   busy = true;
   selectedOpts.width = imgPreloader.width;
   selectedOpts.height = imgPreloader.height;
   $("<img />").attr({
    'id' : 'fancybox-img',
    'src' : imgPreloader.src,
    'alt' : selectedOpts.title
   }).appendTo( tmp );
   fancybox_show();
  },
  fancybox_start = function() {
   fancybox_abort();
   var obj = selectedArray[ selectedIndex ],
    href, 
    type, 
    title,
    str,
    emb,
    selector,
    data;
   selectedOpts = $.extend({}, $.fn.fancybox.defaults, (typeof $(obj).data('fancybox') == 'undefined' ? selectedOpts : $(obj).data('fancybox')));
   title = obj.title || $(obj).title || selectedOpts.title || '';
   
   if (obj.nodeName && !selectedOpts.orig) {
    selectedOpts.orig = $(obj).children("img:first").length ? $(obj).children("img:first") : $(obj);
   }
   if (title === '' && selectedOpts.orig) {
    title = selectedOpts.orig.attr('alt');
   }
   if (obj.nodeName && (/^(?:javascript|#)/i).test(obj.href)) {
    href = selectedOpts.href || null;
   } else {
    href = selectedOpts.href || obj.href || null;
   }
   if (selectedOpts.type) {
    type = selectedOpts.type;
    if (!href) {
     href = selectedOpts.content;
    }
    
   } else if (selectedOpts.content) {
    type = 'html';
   } else if (href) {
    if (href.match(imgRegExp)) {
     type = 'image';
    } else if (href.match(swfRegExp)) {
     type = 'swf';
    } else if ($(obj).hasClass("iframe")) {
     type = 'iframe';
    } else if (href.match(/#/)) {
     obj = href.substr(href.indexOf("#"));
     type = $(obj).length > 0 ? 'inline' : 'ajax';
    } else {
     type = 'ajax';
    }
   } else {
    type = 'inline';
   }
   selectedOpts.type = type;
   selectedOpts.href = href;
   selectedOpts.title = title;
   if (selectedOpts.autoDimensions && selectedOpts.type !== 'iframe' && selectedOpts.type !== 'swf') {
    selectedOpts.width  = 'auto';
    selectedOpts.height  = 'auto';
   }
   if (selectedOpts.modal) {
    selectedOpts.overlayShow  = true;
    selectedOpts.hideOnOverlayClick = false;
    selectedOpts.hideOnContentClick = false;
    selectedOpts.enableEscapeButton = false;
    selectedOpts.showCloseButton = false;
   }
   if ($.isFunction(selectedOpts.onStart)) {
    if (selectedOpts.onStart(selectedArray, selectedIndex, selectedOpts) === false) {
     busy = false;
     return;
    }
   }
   tmp.css('padding', (shadow + selectedOpts.padding + selectedOpts.margin));
   $('.fancybox-inline-tmp').unbind('fancybox-cancel').bind('fancybox-change', function() {
    $(this).replaceWith(inner.children());
   });
   switch (type) {
    case 'html' :
     tmp.html( selectedOpts.content );
     fancybox_process_inline();
    break;
    case 'inline' :
     $('<div class="fancybox-inline-tmp" />').hide().insertBefore( $(obj) ).bind('fancybox-cleanup', function() {
      $(this).replaceWith(inner.children());
     }).bind('fancybox-cancel', function() {
      $(this).replaceWith(tmp.children());
     });
     $(obj).appendTo(tmp);
     fancybox_process_inline();
    break;
    case 'image':
     busy = false;
     $.fancybox.showActivity();
     imgPreloader = new Image();
     imgPreloader.onerror = function() {
      fancybox_error();
     };
     imgPreloader.onload = function() {
      imgPreloader.onerror = null;
      imgPreloader.onload = null;
      fancybox_process_image();
     };
     imgPreloader.src = href;
  
    break;
    case 'swf':
     str = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + selectedOpts.width + '" height="' + selectedOpts.height + '"><param name="movie" value="' + href + '"></param>';
     emb = '';
     
     $.each(selectedOpts.swf, function(name, val) {
      str += '<param name="' + name + '" value="' + val + '"></param>';
      emb += ' ' + name + '="' + val + '"';
     });
     str += '<embed src="' + href + '" type="application/x-shockwave-flash" width="' + selectedOpts.width + '" height="' + selectedOpts.height + '"' + emb + '></embed></object>';
     tmp.html(str);
     fancybox_process_inline();
    break;
    case 'ajax':
     selector = href.split('#', 2);
     data  = selectedOpts.ajax.data || {};
     if (selector.length > 1) {
      href = selector[0];
      if (typeof data == "string") {
       data += '&selector=' + selector[1];
      } else {
       data.selector = selector[1];
      }
     }
     busy = false;
     $.fancybox.showActivity();
     ajaxLoader = $.ajax($.extend(selectedOpts.ajax, {
      url  : href,
      data : data,
      error : fancybox_error,
      success : function(data, textStatus, XMLHttpRequest) {
       if (ajaxLoader.status == 200) {
        tmp.html( data );
        fancybox_process_inline();
       }
      }
     }));
    break;
    case 'iframe' :
     $('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" scrolling="' + selectedOpts.scrolling + '" src="' + selectedOpts.href + '"></iframe>').appendTo(tmp);
     fancybox_show();
    break;
   }
  },
  fancybox_animate_loading = function() {
   if (!loading.is(':visible')){
    clearInterval(loadingTimer);
    return;
   }
   $('div', loading).css('top', (loadingFrame * -40) + 'px');
   loadingFrame = (loadingFrame + 1) % 12;
  },
  fancybox_init = function() {
   if ($("#fancybox-wrap").length) {
    return;
   }
   $('body').append(
    tmp   = $('<div id="fancybox-tmp"></div>'),
    loading  = $('<div id="fancybox-loading"><div></div></div>'),
    overlay  = $('<div id="fancybox-overlay"></div>'),
    wrap  = $('<div id="fancybox-wrap"></div>')
   );
   if (!$.support.opacity) {
    wrap.addClass('fancybox-ie');
    loading.addClass('fancybox-ie');
   }
   outer = $('<div id="fancybox-outer"></div>')
    .append('<div class="fancy-bg" id="fancy-bg-n"></div><div class="fancy-bg" id="fancy-bg-ne"></div><div class="fancy-bg" id="fancy-bg-e"></div><div class="fancy-bg" id="fancy-bg-se"></div><div class="fancy-bg" id="fancy-bg-s"></div><div class="fancy-bg" id="fancy-bg-sw"></div><div class="fancy-bg" id="fancy-bg-w"></div><div class="fancy-bg" id="fancy-bg-nw"></div>')
    .appendTo( wrap );
   outer.append(
    inner  = $('<div id="fancybox-inner"></div>'),
    close  = $('<a id="fancybox-close"></a>'),
    nav_left = $('<a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a>'),
    nav_right = $('<a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a>')
   );
   close.click($.fancybox.close);
   loading.click($.fancybox.cancel);
   nav_left.click(function(e) {
    e.preventDefault();
    $.fancybox.prev();
   });
   nav_right.click(function(e) {
    e.preventDefault();
    $.fancybox.next();
   });
   if (isIE6) {
    overlay.get(0).style.setExpression('height', "document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'");
    loading.get(0).style.setExpression('top',  "(-20 + (document.documentElement.clientHeight ? document.documentElement.clientHeight/2 : document.body.clientHeight/2 ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop )) + 'px'");
    outer.prepend('<iframe id="fancybox-hide-sel-frame" src="javascript:\'\';" scrolling="no" frameborder="0" ></iframe>');
   }
  };
 /*
  * Public methods 
  */
 $.fn.fancybox = function(options) {
  $(this)
   .data('fancybox', $.extend({}, options, ($.metadata ? $(this).metadata() : {})))
   .unbind('click.fb').bind('click.fb', function(e) {
    e.preventDefault();
    if (busy) {
     return;
    }
    busy = true;
    $(this).blur();
    selectedArray = [];
    selectedIndex = 0;
    var rel = $(this).attr('rel') || '';
    if (!rel || rel == '' || rel === 'nofollow') {
     selectedArray.push(this);
    } else {
     selectedArray = $("a[rel=" + rel + "], area[rel=" + rel + "]");
     selectedIndex = selectedArray.index( this );
    }
    fancybox_start();
    return false;
   });
  return this;
 };
 $.fancybox = function(obj) {
  if (busy) {
   return;
  }
  busy = true;
  var opts = typeof arguments[1] !== 'undefined' ? arguments[1] : {};
  selectedArray = [];
  selectedIndex = opts.index || 0;
  if ($.isArray(obj)) {
   for (var i = 0, j = obj.length; i < j; i++) {
    if (typeof obj[i] == 'object') {
     $(obj[i]).data('fancybox', $.extend({}, opts, obj[i]));
    } else {
     obj[i] = $({}).data('fancybox', $.extend({content : obj[i]}, opts));
    }
   }
   selectedArray = jQuery.merge(selectedArray, obj);
  } else {
   if (typeof obj == 'object') {
    $(obj).data('fancybox', $.extend({}, opts, obj));
   } else {
    obj = $({}).data('fancybox', $.extend({content : obj}, opts));
   }
   selectedArray.push(obj);
  }
  if (selectedIndex > selectedArray.length || selectedIndex < 0) {
   selectedIndex = 0;
  }
  fancybox_start();
 };
 $.fancybox.showActivity = function() {
  clearInterval(loadingTimer);
  loading.show();
  loadingTimer = setInterval(fancybox_animate_loading, 66);
 };
 $.fancybox.hideActivity = function() {
  loading.hide();
 };
 $.fancybox.next = function() {
  return $.fancybox.pos( currentIndex + 1);
 };
 
 $.fancybox.prev = function() {
  return $.fancybox.pos( currentIndex - 1);
 };
 $.fancybox.pos = function(pos) {
  if (busy) {
   return;
  }
  pos = parseInt(pos, 10);
  if (pos > -1 && currentArray.length > pos) {
   selectedIndex = pos;
   fancybox_start();
  }
  if (currentOpts.cyclic && currentArray.length > 1 && pos < 0) {
   selectedIndex = currentArray.length - 1;
   fancybox_start();
  }
  if (currentOpts.cyclic && currentArray.length > 1 && pos >= currentArray.length) {
   selectedIndex = 0;
   fancybox_start();
  }
  return;
 };
 $.fancybox.cancel = function() {
  if (busy) {
   return;
  }
  busy = true;
  $.event.trigger('fancybox-cancel');
  fancybox_abort();
  if (selectedOpts && $.isFunction(selectedOpts.onCancel)) {
   selectedOpts.onCancel(selectedArray, selectedIndex, selectedOpts);
  }
  busy = false;
 };
 // Note: within an iframe use - parent.$.fancybox.close();
 $.fancybox.close = function() {
  if (busy || wrap.is(':hidden')) {
   return;
  }
  busy = true;
  if (currentOpts && $.isFunction(currentOpts.onCleanup)) {
   if (currentOpts.onCleanup(currentArray, currentIndex, currentOpts) === false) {
    busy = false;
    return;
   }
  }
  fancybox_abort();
  $(close.add( nav_left ).add( nav_right )).hide();
  $('#fancybox-title').remove();
  wrap.add(inner).add(overlay).unbind();
  $(window).unbind("resize.fb scroll.fb");
  $(document).unbind('keydown.fb');
  function _cleanup() {
   overlay.fadeOut('fast');
   wrap.hide();
   $.event.trigger('fancybox-cleanup');
   inner.empty();
   if ($.isFunction(currentOpts.onClosed)) {
    currentOpts.onClosed(currentArray, currentIndex, currentOpts);
   }
   currentArray = selectedOpts = [];
   currentIndex = selectedIndex = 0;
   currentOpts  = selectedOpts = {};
   busy = false;
  }
  inner.css('overflow', 'hidden');
  if (currentOpts.transitionOut == 'elastic') {
   start_pos = fancybox_get_zoom_from();
   var pos = wrap.position();
   final_pos = {
    top  : pos.top ,
    left : pos.left,
    width : wrap.width(),
    height : wrap.height()
   };
   if (currentOpts.opacity) {
    final_pos.opacity = 1;
   }
   fx.prop = 1;
   $(fx).animate({ prop: 0 }, {
     duration : currentOpts.speedOut,
     easing  : currentOpts.easingOut,
     step  : fancybox_draw,
     complete : _cleanup
   });
  } else {
   wrap.fadeOut( currentOpts.transitionOut == 'none' ? 0 : currentOpts.speedOut, _cleanup);
  }
 };
 $.fancybox.resize = function() {
  var c, h;
  
  if (busy || wrap.is(':hidden')) {
   return;
  }
  busy = true;
  c = inner.wrapInner("<div style='overflow:auto'></div>").children();
  h = c.height();
  wrap.css({height: h + (currentOpts.padding * 2) + titleh});
  inner.css({height: h});
  c.replaceWith(c.children());
  $.fancybox.center();
 };
 $.fancybox.center = function() {
  busy = true;
  var view = fancybox_get_viewport(),
   margin = currentOpts.margin,
   to  = {};
  to.top = view[3] + ((view[1] - ((wrap.height() - titleh) + (shadow * 2 ))) * 0.5);
  to.left = view[2] + ((view[0] - (wrap.width() + (shadow * 2 ))) * 0.5);
  to.top = Math.max(view[3] + margin, to.top);
  to.left = Math.max(view[2] + margin, to.left);
  wrap.css(to);
  busy = false;
 };
 $.fn.fancybox.defaults = {
  padding    : 10,
  margin    : 20,
  opacity    : false,
  modal    : false,
  cyclic    : false,
  scrolling   : 'auto', // 'auto', 'yes' or 'no'
  width    : 560,
  height    : 340,
  autoScale   : true,
  autoDimensions  : true,
  centerOnScroll  : false,
  ajax    : {},
  swf     : { wmode: 'transparent' },
  hideOnOverlayClick : true,
  hideOnContentClick : false,
  overlayShow   : true,
  overlayOpacity  : 0.3,
  overlayColor  : '#666',
  titleShow   : true,
  titlePosition  : 'outside', // 'outside', 'inside' or 'over'
  titleFormat   : null,
  transitionIn  : 'fade', // 'elastic', 'fade' or 'none'
  transitionOut  : 'fade', // 'elastic', 'fade' or 'none'
  speedIn    : 300,
  speedOut   : 300,
  changeSpeed   : 300,
  changeFade   : 'fast',
  easingIn   : 'swing',
  easingOut   : 'swing',
  showCloseButton  : true,
  showNavArrows  : true,
  enableEscapeButton : true,
  onStart    : null,
  onCancel   : null,
  onComplete   : null,
  onCleanup   : null,
  onClosed   : null
 };
 $(document).ready(function() {
  fancybox_init();
 });
})(jQuery);

//-----------------------------------------------------------------------------
// jquery.easing.js - 15489
//-----------------------------------------------------------------------------
/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright &Acirc;&copy; 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/
// t: current time, b: begInnIng value, c: change In value, d: duration
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('h.i[\'1a\']=h.i[\'z\'];h.O(h.i,{y:\'D\',z:9(x,t,b,c,d){6 h.i[h.i.y](x,t,b,c,d)},17:9(x,t,b,c,d){6 c*(t/=d)*t+b},D:9(x,t,b,c,d){6-c*(t/=d)*(t-2)+b},13:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t+b;6-c/2*((--t)*(t-2)-1)+b},X:9(x,t,b,c,d){6 c*(t/=d)*t*t+b},U:9(x,t,b,c,d){6 c*((t=t/d-1)*t*t+1)+b},R:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t+b;6 c/2*((t-=2)*t*t+2)+b},N:9(x,t,b,c,d){6 c*(t/=d)*t*t*t+b},M:9(x,t,b,c,d){6-c*((t=t/d-1)*t*t*t-1)+b},L:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t*t+b;6-c/2*((t-=2)*t*t*t-2)+b},K:9(x,t,b,c,d){6 c*(t/=d)*t*t*t*t+b},J:9(x,t,b,c,d){6 c*((t=t/d-1)*t*t*t*t+1)+b},I:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t*t*t+b;6 c/2*((t-=2)*t*t*t*t+2)+b},G:9(x,t,b,c,d){6-c*8.C(t/d*(8.g/2))+c+b},15:9(x,t,b,c,d){6 c*8.n(t/d*(8.g/2))+b},12:9(x,t,b,c,d){6-c/2*(8.C(8.g*t/d)-1)+b},Z:9(x,t,b,c,d){6(t==0)?b:c*8.j(2,10*(t/d-1))+b},Y:9(x,t,b,c,d){6(t==d)?b+c:c*(-8.j(2,-10*t/d)+1)+b},W:9(x,t,b,c,d){e(t==0)6 b;e(t==d)6 b+c;e((t/=d/2)<1)6 c/2*8.j(2,10*(t-1))+b;6 c/2*(-8.j(2,-10*--t)+2)+b},V:9(x,t,b,c,d){6-c*(8.o(1-(t/=d)*t)-1)+b},S:9(x,t,b,c,d){6 c*8.o(1-(t=t/d-1)*t)+b},Q:9(x,t,b,c,d){e((t/=d/2)<1)6-c/2*(8.o(1-t*t)-1)+b;6 c/2*(8.o(1-(t-=2)*t)+1)+b},P:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d)==1)6 b+c;e(!p)p=d*.3;e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);6-(a*8.j(2,10*(t-=1))*8.n((t*d-s)*(2*8.g)/p))+b},H:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d)==1)6 b+c;e(!p)p=d*.3;e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);6 a*8.j(2,-10*t)*8.n((t*d-s)*(2*8.g)/p)+c+b},T:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d/2)==2)6 b+c;e(!p)p=d*(.3*1.5);e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);e(t<1)6-.5*(a*8.j(2,10*(t-=1))*8.n((t*d-s)*(2*8.g)/p))+b;6 a*8.j(2,-10*(t-=1))*8.n((t*d-s)*(2*8.g)/p)*.5+c+b},F:9(x,t,b,c,d,s){e(s==u)s=1.l;6 c*(t/=d)*t*((s+1)*t-s)+b},E:9(x,t,b,c,d,s){e(s==u)s=1.l;6 c*((t=t/d-1)*t*((s+1)*t+s)+1)+b},16:9(x,t,b,c,d,s){e(s==u)s=1.l;e((t/=d/2)<1)6 c/2*(t*t*(((s*=(1.B))+1)*t-s))+b;6 c/2*((t-=2)*t*(((s*=(1.B))+1)*t+s)+2)+b},A:9(x,t,b,c,d){6 c-h.i.v(x,d-t,0,c,d)+b},v:9(x,t,b,c,d){e((t/=d)<(1/2.k)){6 c*(7.q*t*t)+b}m e(t<(2/2.k)){6 c*(7.q*(t-=(1.5/2.k))*t+.k)+b}m e(t<(2.5/2.k)){6 c*(7.q*(t-=(2.14/2.k))*t+.11)+b}m{6 c*(7.q*(t-=(2.18/2.k))*t+.19)+b}},1b:9(x,t,b,c,d){e(t<d/2)6 h.i.A(x,t*2,0,c,d)*.5+b;6 h.i.v(x,t*2-d,0,c,d)*.5+c*.5+b}});',62,74,'||||||return||Math|function|||||if|var|PI|jQuery|easing|pow|75|70158|else|sin|sqrt||5625|asin|||undefined|easeOutBounce|abs||def|swing|easeInBounce|525|cos|easeOutQuad|easeOutBack|easeInBack|easeInSine|easeOutElastic|easeInOutQuint|easeOutQuint|easeInQuint|easeInOutQuart|easeOutQuart|easeInQuart|extend|easeInElastic|easeInOutCirc|easeInOutCubic|easeOutCirc|easeInOutElastic|easeOutCubic|easeInCirc|easeInOutExpo|easeInCubic|easeOutExpo|easeInExpo||9375|easeInOutSine|easeInOutQuad|25|easeOutSine|easeInOutBack|easeInQuad|625|984375|jswing|easeInOutBounce'.split('|'),0,{}))
/*
 *
 * TERMS OF USE - EASING EQUATIONS
 * 
 * Open source under the BSD License. 
 * 
 * Copyright &Acirc;&copy; 2001 Robert Penner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */


//-----------------------------------------------------------------------------
// load-script.js - 15161
// Dynamically add a javascript source file to the DOM
//-----------------------------------------------------------------------------
function load_script(src) {
    $('<script></script>')
        .attr({
            type: 'text/javascript',
            src: src
        })
        .appendTo('body');
}

//-----------------------------------------------------------------------------
// load-scripts.js - 15162
// Dynamically load scripts as they are required by specific pages
//-----------------------------------------------------------------------------
function load_scripts()
{
    if ($('body').hasClass('donatepages') && $('form#standard').length)
    {
        load_script("/assets/js/donate-form.js");
        load_script("/assets/php/client-side-validation.php?data=oneoff-input.php");
    }
    else if ($('body').attr('id') == 'donate')
    {
        load_script("/assets/js/donate-landing-form.js");
    }
}

//-----------------------------------------------------------------------------
// google analytics - 13335
// Set up google analytics for page views, forms, and events
//-----------------------------------------------------------------------------
var _gaq = _gaq || [];

_gaq.push(['_setAccount',      'UA-1001179-1']);
_gaq.push(['_setAllowLinker',  true]);
_gaq.push(['_setAllowHash',    false]);

var dom = window.location.host;
//console.log(dom);

if (dom != 'www.savethechildren.org.uk' || dom != 'reddot.savethechildren.org.uk')
{
    _gaq.push(['_setDomainName', 'none']);
}
else
{
    _gaq.push(['_setDomainName', '.savethechildren.org.uk']);
}


if (typeof(page_type) != 'undefined' && (page_type == '404' || page_type == '410'))
{
    _gaq.push(['_trackEvent', "Error", page_type, window.location.pathname + window.location.search]);
}
else if (typeof(custom_page_view) != 'undefined')
{
    _gaq.push(['_trackPageview', custom_page_view]);
}
else
{
    _gaq.push(['_trackPageview']);
}


/* E-commerce stuff - for secure trading thank you pages */

if (typeof(st_data) != 'undefined')
{
    _gaq.push(['_addTrans',
        st_data.oid,      // order ID - required
        st_data.affil,    // affiliation or store name
        st_data.total,    // total - required
        st_data.tax,      // tax
        st_data.shipping, // shipping
        st_data.city,     // city
        st_data.state,    // state or province
        st_data.country   // country
    ]);

    _gaq.push(['_addItem',
        st_data.oid,      // order ID - required
        st_data.sku,      // SKU/code
        st_data.product,  // product name
        st_data.category, // category or variation
        st_data.unit,     // unit price - required
        st_data.quantity  // quantity - required
    ]);

    _gaq.push(['_trackTrans']);
}


(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();


function init_google_tracking()
{
    // Forms

    $('form').submit(function() {
        _gaq.push(['_linkByPost', this]);
    });


    // Events

    $('#tabs .home').click(function() {
        _gaq.push(['_trackEvent', "Click", "Home tab"]);
    });

    $('#logo').click(function() {
        _gaq.push(['_trackEvent', "Click", "Logo"]);
    });

    $('#carousel .tabs a').click(function() {
        _gaq.push(['_trackEvent', "Click", "Carousel tab", window.location.pathname + $(this).attr('href')]);
    });

    $('#carousel .panel a').click(function() {
        _gaq.push(['_trackEvent', "Click", "Link in carousel panel", $(this).attr('href')]);
    });

    $('#hpah a').click(function() {
        _gaq.push(['_trackEvent', "Click", "How people are helping link", $(this).attr('href')]);
    });

    $('#donate-boxes img').click(function(e) {
        $a = $(this).parent();

        var query_string = $a[0].search.substr(1);
        var params = query_string.split('&');

        for (var p in params)
        {
            var parts = params[p].split('=');

            if (parts[0] == 'reg-amount' || parts[0] == 'one-amount')
            {
                _gaq.push(['_trackEvent', "Click", parts[0], parts[1]]);
                break;
            }
        }
    });
}

//-----------------------------------------------------------------------------
// giftaid-calc.js - 10252
//-----------------------------------------------------------------------------
function update_giftaid_example(val, multiplier, defval)
{
    var valid = val.match(/^\d+$/) || val.match(/^\d+\.\d*$/);
    val = valid ? val : defval;

    var article = valid ? 'your' : 'a';
    var value = '&pound;' + val;
    var extra = "" + (multiplier * val);

    $('#donation-article').text(article);
    $('#donation-value-feedback').html(value);

    var i = extra.indexOf('.');

    if (i > -1)
    {
        var pennies = extra.substr(i + 1);

        if (pennies.length == 1)
        {
            extra += '0';
        }
        else if (pennies.length > 2)
        {
            extra = extra.substr(0, i + 3);
        }
    }

    $('#donation-extra-feedback').html("&pound;" + extra);
}

//-----------------------------------------------------------------------------
// donate-faqs.js - 10146
//-----------------------------------------------------------------------------
function setup_donate_faqs()
{
    $('#faqs dd').hide();
    $('#faqs dt').css('cursor', 'pointer');
    $('#faqs > *').css('padding-left', '16px');
    $('#faqs dt').data('state', false);

    $('#faqs dt').each(function() {
        $(this).addClass('closed');
    
        $(this).click(function() {
            var state = $(this).data('state');
            $(this).removeClass("open");
            $(this).removeClass("closed");
            $(this).addClass(state ? "closed" : "open");
            $(this).data("state", !state);
            $(this).next('dd').toggle();
        });
    });
}

//-----------------------------------------------------------------------------
// textsize-widget.js - 11289
// Adds a "+/-" widget to each page that allows font-size to be changed
//-----------------------------------------------------------------------------
function text_size_widget()
{
    var markup = '<div id="resize">';
    markup += '<span>Text size</span><ul>';
    markup += '<li><a title="Decrease text size" id="decrease-text-size" href="#"></a></li>';
    markup += '<li><a title="Increase text size" id="increase-text-size" href="#"></a></li>';
    markup += '</ul></div>';

    $('#tabs').after(markup);

    $('#resize a').prettyTooltip();

    if (c = $.cookie('fontsize'))
    {
        $('body').css({ fontSize: c + 'px' });
    }

    $('#increase-text-size').click(function() {
        $('body').css({
            fontSize: function(i, v) {
                v = parseInt(v) + 1;
                $.cookie('fontsize', v, { path: '/' });
                _gaq.push(['_trackEvent', "Click", "Text size", "Increase", v]);
                return v;
            }
        });

        return false;
    });

    $('#decrease-text-size').click(function() {
        $('body').css({
            fontSize: function(i, v) {
                v = parseInt(v) - 1;
                $.cookie('fontsize', v, { path: '/' });
                _gaq.push(['_trackEvent', "Click", "Text size", "Decrease", v]);
                return v;
            }
        });

        return false;
    });

    $(window).keypress(function(ev) {
        if (ev.ctrlKey && ev.charCode == 48)
        {
            $('body').css('fontSize', '');
            $.cookie('fontsize', '', { path: '/' });
        }
    });
};

//-----------------------------------------------------------------------------
// facebook-like.js - 13302
//-----------------------------------------------------------------------------
function facebook_like_inject()
{
    // layout one of 'standard', 'button_count', 'box_count'
    // action either 'like' or 'recommend'
    // colorscheme either 'light' or 'dark'

    var opts = {
        layout:     'standard',
        show_faces: 'true',
        action: 'like',
        colorscheme: 'light',
        height: 80
    };

    add_facebook_like('#facebook-like', opts);
}

function add_facebook_like(el, opts)
{
    var $el = $(el);

    if (!$el.length)
    {
        return;
    }

    var width = $el.width();

    //var width   = opts['width']   ? opts['width']   : 450;
    var height  = opts['height']  ? opts['height']  : 80;

    var url = encodeURI(window.location);

    for (var o in opts)
    {
        url += '&amp;' + o + '=' + opts[o];
    }

    $('<iframe src="http://www.facebook.com/plugins/like.php?href=' + url + '"></iframe>')
        .attr({
            scrolling: 'no',
            frameBorder: 0,
            allowTransparency: 'true'
        }).css({
            border:    'none',
            overflow:  'hidden',
            width:     width + 'px',
            height:    height + 'px'
        }).appendTo(el);
}

//-----------------------------------------------------------------------------
// nav-highlight.js - 9540
// Highlight links on this page to itself - e.g. in navigation
//-----------------------------------------------------------------------------
function nav_highlight()
 {
    // Get rid of "http://"
    loc = location.href.substring(7);

    // Get rid of domain name
    loc = loc.substring(loc.indexOf("/"));

    // Get rid of fragment identifier
    var i = loc.indexOf("#");
    if (i > -1) loc = loc.substring(0, i);

    // Highlight navigator links to this page
    $("#navigator a[href='" + loc + "']").addClass('now');

    var loc_parent = $('html > head > link[rel="up"]').attr('href');
    $("#navigator a[href='" + loc_parent + "']").addClass('now');

    // Highlight footer sitemap links to this page
    $("#footer-sitemap a[href='" + loc + "']").addClass('now');
}

//-----------------------------------------------------------------------------
// taglinks.js - 10121
// Ensure links to files and external links are tracked via Google Analytics
//-----------------------------------------------------------------------------
function track_files()
{
    $('a').each(function() {
        if (should_track(this))
        {
            $(this).click(function() {
                var str = get_file_tracking_string(this);
                _gaq.push(['_trackPageview', str]);
            });
        }
    });
}

function should_track(link)
{
    return link.protocol == 'mailto:' || $(link).hasClass('pseudo-external') || link.hostname != location.host
        || link.pathname.match(/\.(doc|pdf|xls|ppt|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3)$/);
}

function get_file_tracking_string(link)
{
    var file_path = '';

    if (link.protocol == 'mailto:')
    {
        file_path = '/mail/' + $(link).attr('href').substr(7);
    }
    else
    {
        if (location.host != link.hostname)
        {
            var host = trim(link.hostname, '/');
            file_path = "/external/" + host;
        }

        var path = trim(link.pathname, '/');

        if (path)
            file_path += '/' + path;
    }

    return file_path;
}

//-----------------------------------------------------------------------------
// promo-tracking.js - 11295
// Track promo boxes via google analytics
//-----------------------------------------------------------------------------
function track_promos()
{
    var body_id = $('body').attr('id');

    $('.promo,.promo-wide').each(function() {
        var id = $(this).attr('id');

        if (id)
        {
            promo_tracking(id, body_id);
        }
    });
}

//-----------------------------------------------------------------------------
// quick-donate.js - 8806
// Handle the 'donate amount selection' panel on the main donate page
//-----------------------------------------------------------------------------
function init_quick_donate()
{
    if ($('body').attr('id') == 'donatepage' || $('body').attr('id') == 'donate')
    {
        quick_donate($('body').attr('id'));
    }
}

function quick_donate(id)
{
    $('#gallery').cycle({
        fx:     'fade',
        speed:  2000,
        pager:  '#gallery-nav',
        next: '#gallery'
    });

    var fragment = window.location + '';
    fragment = fragment.substring(fragment.lastIndexOf('#'));

    $('#gallery').css('height', '300px');
    $('#everymonth').click();

    if (fragment != '#regulargiving')
    {
        $('.regulargiving').hide();
    }

    $('.examplesoneoff').hide();

    // Hide unwanted radio buttons
    $('.examplesregular input').css('position', 'absolute');
    $('.examplesregular input').css('left', '-9000px');
    $('.examplesoneoff input').css('position', 'absolute');
    $('.examplesoneoff input').css('left', '-9000px');

    // Add 'regular giving more info' link
    if (id == 'donatepage')
    {
        $('#rglrgiving').before('<a id="rgivingmoreinfo" href="#">How regular giving saves children\'s lives &raquo;</a>');
    }
    else
    {
        $('#everymonth').parent().append('(<a id="rgivingmoreinfo" href="#">how regular giving saves children\'s lives &raquo;</a>)');
    }

    $('#onceonly').click(function() {
        $('.regulargiving').slideUp('slow');

        if (id == 'donatepage')
        {
            $('#rgivingmoreinfo').html('How regular giving saves children\'s lives &raquo;');
        }
        else
        {
            $('#rgivingmoreinfo').html('how regular giving saves children\'s lives &raquo;');
        }

        $('.examplesregular').hide();
        $('.examplesoneoff').show();
    });

    $('#everymonth').click(function() {
        $('.examplesoneoff').hide();
        $('.examplesregular').show();
    });

    $('#rgivingmoreinfo').click(function() {
        if ($('.regulargiving').is(':visible'))
        {
            $('.regulargiving').slideUp('slow');

            if (id == 'donatepage')
            {
                $('#rgivingmoreinfo').html('How regular giving saves children\'s lives &raquo;');
            }
            else
            {
                $('#rgivingmoreinfo').html('how regular giving saves children\'s lives &raquo;');
            }
        }
        else
        {
            $('.regulargiving').slideDown('slow');
            _gaq.push(['_trackEvent', "Click", "Regular giving more info"]);

            if (id == 'donatepage')
            {
                $('#rgivingmoreinfo').html('&laquo; Children need you, not just today but every day');
            }
            else
            {
                $('#rgivingmoreinfo').html('&laquo; children need you, not just today but every day');
            }
        }
        return false;
    });

    $('.examplesregular input[type=radio]').click(function() {
        $('#donate-amount').val($(this).val());
        id = this.id;

        // highlight the label too
        $("label").removeClass('current').filter("[for=" + id + "]").addClass("current");

        // ... and record a google analytics 'hit'
        //urchinTracker("/donate-amount/" + $(this).val());
        _gaq.push(['_trackEvent', "Main donate page", "Click", "Regular giving amount", $(this).val()]);
    });

    $('.examplesoneoff input[type=radio]').click(function() {
        $('#donate-amount').val($(this).val());
        id = this.id;

        // highlight the label too
        $("label").removeClass('current').filter("[for=" + id + "]").addClass("current");

        // ... and record a google analytics 'hit'
        //urchinTracker("/donate-amount/" + $(this).val());
        _gaq.push(['_trackEvent', "Main donate page", "Click", "One-off amount", $(this).val()]);
    });

    $('#donate-amount').change(function() {
        $("label").removeClass('current');
    });
}
 
 
 

//-----------------------------------------------------------------------------
// sidebar-quick-donate.js - 15071
// Ensures that the sidebar quick donate form works properly in terms of selecting the 'other' box if an 'other' amount is entered
//-----------------------------------------------------------------------------
function quick_donate_other()
 {
    $('.quick-donate #other_amount').keypress(function() {
        $('.quick-donate #amount-other').attr('checked', 'checked');
    });
}

//-----------------------------------------------------------------------------
// Auto gallery - 11681
//-----------------------------------------------------------------------------
function auto_gallery()
 {
    $ag = $('.auto-gallery');

    if ($ag.length)
    {
        $ag.cycle({
            fx:     'fade',
            speed:  2000
        });
    }
}

//-----------------------------------------------------------------------------
// gallery.js - 11338
// Apply jQuery Cycle plugin to create photo galleries
//-----------------------------------------------------------------------------
function init_photo_galleries()
 {
    var $pics = $('.pics');
    $pics.addClass('image-gallery');

    var $pics_nav = $('.pics-nav');
    $pics_nav.addClass('image-gallery-nav');
    $pics.find('div span').hide();

    var g = 0;

    $pics.each(function() {
        g++;

        var $gallery = $(this);
        var id = $gallery.attr('id');

        var height = $gallery.find('img').outerHeight();

        $gallery.css('height', height + 'px');

        if (!id)
        {
            id = 'gallery-' + g;
            $gallery.attr('id', id);
        }

        var $gnav = $gallery.nextAll('.pics-nav:first');
        var nid = $gnav.attr('id');

        if (!nid)
        {
            nid = 'gallery-nav-' + g;
            $gnav.attr('id', nid);
        }

        $gallery.cycle({
            fx:       'fade',
            speed:    'slow',
            timeout:  0,
            pager:    '#' + nid,
            next:     '#' + id,

            // callback fn that creates a thumbnail to use as pager anchor
            pagerAnchorBuilder: function(idx, slide)
            {
                var imgs = slide.getElementsByTagName("img");
                return '<li><a href="#"><img src="' + imgs[0].src + '" width="50" height="32"></a></li>';
            },

            'before': function()
            {
                var tmp = this.getElementsByTagName("span");
                var cap = tmp[0] ? tmp[0].innerHTML : '';
                $(this).parent().nextAll('.gallery-caption:first').html(cap);
            }
        });
    });
}

//-----------------------------------------------------------------------------
// new dynamic gallery - 13205
//-----------------------------------------------------------------------------
function dynamic_gallery()
 {
    $('.gallery').each(function() {
        $gallery = $(this);

        /* Clean up RedDot's mess */
        $('> p > img', $gallery).unwrap();

        /* Wrap images and captions in structure */
        $('> img', $gallery).each(function() {
            $caption = $(this).next("p");
            $(this).wrap('<li></li>');

            if ($caption.length)
            {
                $(this).after($caption[0]);
            }
        });

        var $lis = $('> li', $gallery);

        $ul = $('<ul class="gallery">').appendTo($gallery).append($lis).unwrap();

        var height = $ul.find('img').outerHeight()

        $ul.css('height', height + 'px');

        $ul.cycle({
            fx:       'fade',
            speed:    2000,
            timeout:  0,
            next:     '.gallery',
    
            before: function() {
                var tmp = this.getElementsByTagName("p");
                var caption = tmp[0] ? tmp[0].innerHTML : '';
                $(this).parent().nextAll('.caption:first').html(caption);
            }
        }).find('p').hide();
    });
}


//-----------------------------------------------------------------------------
// global maps - 11506
//-----------------------------------------------------------------------------
var map;
var points = [];

// TODO Rename this function to something less generic!

function initialize() {
    var mapLat   = 21.3;
    var mapLong  = 10;
    var mapZoom  = 2;

    var latlng = new google.maps.LatLng(mapLat, mapLong);

    var windowOpts = {
        position: latlng,
        maxWidth: 300
    };

    infoWindow = new google.maps.InfoWindow(windowOpts);

    var myOptions = {
        zoom: mapZoom,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.HYBRID,
        scrollwheel: false,
        mapTypeControl: false
    };

    map = new google.maps.Map(document.getElementById("map"), myOptions);

    for (var m in markers)
    {
        var marker = markers[m];
        var html = '';

        if (!marker.lat) continue;

        html += marker.img ? '<img style="float: left; margin-right: 10px; margin-bottom: 10px;" src="' + marker.img + '">' : '';
        marker.title = marker.title.replace("&#244;", 'o');

        html += '<h2 style="margin-top: 0;"> <a href="' + marker.url +'">' + marker.title + '</a></h2>';

        if (marker.pop)
        {
            html += '<p style="margin: 0; font-size: 12px;">Population: ' + marker.pop;
            html += marker.ypop ? ' (under 18: ' + marker.ypop + '%)' : '';
            html += '</p>';
        }

        html += '<p style="margin: 0; font-size: 12px;">' + marker.intro + '</p>';
        markers[m].html = html;
        
        add_info_marker(m, markers[m].lat, markers[m].lng, markers[m].title, markers[m].html);
    }

    for (var m in markers)
    {
        if (markers[m].featured)
        {
            var pos = new google.maps.LatLng(markers[m].lat, markers[m].lng);
            infoWindow.setPosition(pos);
            infoWindow.setContent(markers[m].html);
            map.setCenter(pos);
            infoWindow.open(map);
            break;
        }
    }
}


function add_info_marker(id, lat, lng, title, content)
{
    var point = new google.maps.LatLng(lat, lng);

    marker = new google.maps.Marker({
        position: point,
        title: title
    });

    marker.id = id;
    marker.setMap(map);

    google.maps.event.addListener(marker, 'click', function() {
        var marker = markers[this.id];
        infoWindow.setContent(content);
        infoWindow.setPosition(this.getPosition());
        infoWindow.open(map, this);
    });
}


function init_maps()
 {
    switch ($('body').attr('id'))
    {
    //case 'cef':
    case 'emergencies':
    case 'where-we-work':
        load_script('http://maps.google.com/maps/api/js?sensor=false&callback=initialize');
        $("#ui-tabs").tabs();
        break;

    case 'local-campaigners':
        load_script('http://maps.google.com/maps/api/js?sensor=false&callback=local_campaigners_map');
        break;
    }
}//-----------------------------------------------------------------------------
// regional-map.js - 11368
//-----------------------------------------------------------------------------
function init_regional_maps()
{
    var $map = $('#regional_map');

    if ($map.length)
    {
        mapType = G_HYBRID_MAP;

        if (typeof(mapHeight) == "undefined")
        {
            mapHeight = 400;
        }

        var props = { height: mapHeight + 'px' };

        if (typeof(mapWidth) != "undefined")
        {
            props.width = mapWidth + 'px';
        }

        $map.css(props);

        regional_map_initialize();
    }
}


//-----------------------------------------------------------------------------
// hpah.js - 11483
// Load relevant 'how people are helping' content into appropriate elements
//-----------------------------------------------------------------------------
function load_how_people_are_helping()
 {
    var $hpah = $('#hpah');

    if ($hpah.length)
    {
        var classes = $hpah.attr('class').split(' ');

        for (c in classes)
        {
            if (classes[c].substr(0, 5) == 'hpah-')
            {
                var file = classes[c].substr(5).split('-').join('.') + '.html';
                $hpah.load("/actions/" + file);
                break;
            }
        }
    }
}

//-----------------------------------------------------------------------------
// scroller.js - 12475
// Animated scroll of a list
//-----------------------------------------------------------------------------
function init_scrollers()
{
    var mt = 0;

    $('ul.scroller').each(function() {

        $ul = $(this);
        var height = $ul.find('li:first-child').outerHeight();
        var $li = $ul.find('li:first-child');

        (function() {
            mt--;

            $li.css({
                marginTop: mt + 'px'
            });

            if (mt <= 0 - height)
            {
                mt = 0;
                $li.appendTo($ul).css({marginTop: 0});
                $li = $ul.find('li:first-child');
            }

            setTimeout(arguments.callee, 50);
        })();
    });
}

//-----------------------------------------------------------------------------
// slideshow-ticker.js - 11649
//-----------------------------------------------------------------------------
function init_slideshow_tickers()
 {
    // Break entire ol list into groups of (at most) 6 items
    $('.slideshow-ticker').addClass('after');

    $('.slideshow-ticker ol').each(function() {
        $lis = $(this).find('> li');

        for (var i = 0; i < $lis.length; i += 6)
        {
            var end = i + 6 > $lis.length ? $lis.length : i + 6;
            $lis.slice(i, i + 3).wrapAll("<ul></ul>");
            $lis.slice(i + 3, end).wrapAll("<ul></ul>");
        }

        $uls = $(this).find('> ul');

        for (var j = 0; j < $uls.length; j += 2)
        {
            $uls.slice(j, j + 2).wrapAll("<li></li>");
        }
    });

    $('.slideshow-ticker p').each(function() {
        $next = $(this).next('ol');

        if ($next.length)
        {
            $('<li></li>').prependTo($next).append(this);
        }
        else
        {
            $(this).parent().append('<ol><li></li></ol>');
            $(this).parent().find('ol:last-child li').append($(this));
        }
    });

    $('.slideshow-ticker ol > li').hide();
    $('.slideshow-ticker ol:first > li:first').addClass('current').show();
    $(document).everyTime(3000, slideshow_ticker_cycle);
}

function slideshow_ticker_cycle() {
    $curr = $('.slideshow-ticker ol > li.current');

    if ($curr.is(':last-child'))
    {
        $parent = $curr.parent();

        if ($parent.is(':last-child'))
        {
            $next = $('.slideshow-ticker > ol:first-child > li:first-child')
        }
        else
        {
            $next = $parent.next().find('li:first-child');
        }
    }
    else
    {
        $next = $curr.next();
    }

    $curr.fadeOut(1000, function() {
        $next.fadeIn(1000, function() {
            $curr.removeClass('current');
            $next.addClass('current');
        });
    });
}

//-----------------------------------------------------------------------------
// [170a] - ladder javascript - 10284 - 10284
//-----------------------------------------------------------------------------
function friendship_funday_ladder()
 {
    $('.ff-ladder li').mouseenter(function() {
        if (!$(this).find('p').length)
        {
            var title = $(this).attr('title');
            $(this).attr('title', '');
            $(this).append("<p class='popup'>" + title + "</p>");
            $(this).find("p").fadeIn('fast');
        }
    });

    $('.ff-ladder li').mouseleave(function() {
        if ($(this).find('p').length)
        {
            var title = $(this).find('p').text();
            $(this).attr('title', title);

            $(this).find("p").fadeOut('fast', function () {
                $(this).remove();
            });
        }
    });
}

//-----------------------------------------------------------------------------
// flash-game - little jack - 12793
//-----------------------------------------------------------------------------
function little_jack_game()
{
    $('body#little-jack-game #flash').flash({
        swf: '/assets/movies/game_f7_560x310_php.swf',
        width: 470,
        height: 300,
        flashvars: { animationPath:'http://www.savethechildren.org.uk/en/53_2573.htm' }
    },
    { version: '9.0.0.0' });
}

//-----------------------------------------------------------------------------
// video popups - 12939
//-----------------------------------------------------------------------------
function video_popups()
{
    $('.video-thumbnail').click(function() {
        var width   = 480;
        var height  = 270;

        var left = (screen.width / 2) - (width / 2);
        var top  = (screen.height / 2) - (height / 2) - 80;

        var opts = "width=" + width + ",height=" + height + ",left=" + left + ",top=" + top;
        opts += ",toolbar=0,resizable=no,dialog=yes,titlebar=no,status=no,personalbar=no,menubar=no,location=no";

        window.open(this.href, "newwindow", opts);

        return false;
    });
}

//-----------------------------------------------------------------------------
// moodboards - 13028
//-----------------------------------------------------------------------------
function moodboard_popups()
{
    $('body.moodboards dt a').live('click', function() {
        $.fancybox({
            autoDimensions: false,
            href: this.href,
            transitionIn: 'fade',
            width: 800,
            height: 600,
            padding: 0
        });

        return false;
    });
}

//-----------------------------------------------------------------------------
// new homepage - 13219
//-----------------------------------------------------------------------------
var flash_video_playing = false;
var carousel_delay = 5000;

function init_carousels()
{
    switch ($('body').attr('id'))
    {
        case 'test-new-home':
        case 'news':
            $('.tabs a').click(function(evt) {
                evt.preventDefault();
            });

            $('#carousel').tabs({
                //fx: { duration: 1000, opacity: 'toggle' },

                select: function(event, ui) {
                    if (flash_video_playing)
                    {
                        // record the time so we can restart the video later
                        var id = $('#carousel .panel:not(.ui-tabs-hide)')[0].id;
                        var $fph = $('.flash-player-holder', '#' + id);

                        var fph_id = $fph[0].id;
                        flash_video_pause('#' + fph_id);

                        $('.flash-player-controls', $fph).fadeIn('slow').addClass("flash-player-controls-active");
                    }
                },

                show: function(event, ui)
                {
                    panel = ui.panel;

                    flashObj = $(".flash-container object", panel)[0];
                    var $fph = $('.flash-player-holder', '#' + panel.id);
                    var last_time = $fph.data('video_time');

                    if (flashObj && last_time)
                    {
                        flash_video_buffer_seek('#' + $fph[0].id, last_time);
                        $('.start-image-overlay', $fph).show();
                    }
                }
            })/*.tabs("rotate", carousel_delay).mouseenter(function() {
                $(this).tabs("rotate", 0);
            }).mouseleave(function() {
                if (!flash_video_playing)
                {
                    $(this).tabs("rotate", carousel_delay);
                }
            })*/;

            $('.tabs').fadeIn(1000);

            $('.ui-tabs-nav a').mouseenter(function() {
                $('#carousel').tabs("select", $(this).attr('href'));
            })
            .click(function() {
                panel = $(this).attr('href');
                $panel = $(panel);
                target = $('h2 a', $panel).attr('href');
                window.location = target;
            });
    }

    activate_forms();
}

function activate_forms()
{
    $('#get-updates-form label').each(function() {
        var $for = $('#' + $(this).attr('for'));

        var tag = $for[0].tagName.toLowerCase();
        var type = $for.attr('type');

        if (tag == 'input' && type == 'text')
        {
            $for.addClass('default-text').attr('value', $(this).text());
            $for[0].defaultValue = $(this).text();
            $(this).hide();
        }
        else if (tag == 'select')
        {
            $for.prepend("<option value=''>" + $(this).text() + "</option>");
            $('option:first', $for).attr('selected', 'selected');
            $(this).hide();
        }
    });

    $('#get-updates-form').submit(function() {
        $("input[type=text]", this).each(function() {
            if (this.defaultValue == $(this).val())
            {
                $(this).val("");
            }
        });
    });

    $('form.visit-other-sites select').prepend("<option>Select...</option>").change(function() {
        window.location = $(this).val();
    });

    $('form.visit-other-sites select option:first').attr('selected', 'selected');
}

//-----------------------------------------------------------------------------
// blog-posts.js - 13595
// Display a blog feed
//-----------------------------------------------------------------------------
if (!blog_feeds)
{
    var blog_feeds = [];
}

function init_blog_feeds()
{
    for (var f in blog_feeds)
    {
        var feed = blog_feeds[f];
        show_blog_posts(feed.sel, feed.title, feed.num, feed.opts);
    }
}

function show_blog_posts(el, title, num, opts)
{
    var url = '/blogs/';

    if (opts.category)
    {
        url += 'category/' + opts.category + '/';
    }
    else if (opts.tag)
    {
        url += 'tag/' + opts.tag + '/';
    }

    url += 'feed/';

    //opts.show_meta = opts.show_meta ? opts.show_meta : 1;

    inject_rss(el, title, url, num, opts.title_tag, opts.show_meta);
}

function inject_rss(el, title, url, num, title_tag, show_meta)
{
    $.get(url, function(data) {

        $ul = $(el);

        $(data).find('item').slice(0, num).each(function() {

            var title   = $("title", this).text();
            var url     = $("link", this).text();
            var author  = $("[nodeName=dc:creator]", this).text();
            var date    = $("pubDate", this).text();

            var d = new Date(Date.parse(date));

            date = to_stc_date(d);

            var content = '<a href="' + url + '">' + title + '</a>';

            if (show_meta)
            {
                content += '<p style="margin: 0;" class="date">' + author + " | " + date + "</p>";
            }

            //$li = $('<li></li>').appendTo($ul).append('<a href="' + url + '">' + title + '</a><p class="date">' + author + " | " + date + "</p>");

            $li = $('<li></li>').appendTo($ul).append(content);

        });

        if (title && title_tag)
        {
            $ul.before('<' + title_tag + '>' + title + '</' + title_tag + '>');
        }

    });
}

function to_stc_date(date)
{
    var dayNames    = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ];

    var monthNames  = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ];

    var day_of_week = dayNames[date.getDay()].substr(0, 3);

    var date_of_month = date.getDate();
    date_of_month = date_of_month < 10 ? "0" + date_of_month : date_of_month;

    var month = monthNames[date.getMonth()];

    return day_of_week + " " + date_of_month + " " + month;
}

//-----------------------------------------------------------------------------
// flash-video-hack.js - 13625
//-----------------------------------------------------------------------------
/*
Copyright (c) Copyright (c) 2007, Carl S. Yestrau All rights reserved.
Code licensed under the BSD License: http://www.featureblend.com/license.txt
Version: 1.0.4
*/
var FlashDetect = new function(){
    var self = this;
    self.installed = false;
    self.raw = "";
    self.major = -1;
    self.minor = -1;
    self.revision = -1;
    self.revisionStr = "";
    var activeXDetectRules = [
        {
            "name":"ShockwaveFlash.ShockwaveFlash.7",
            "version":function(obj){
                return getActiveXVersion(obj);
            }
        },
        {
            "name":"ShockwaveFlash.ShockwaveFlash.6",
            "version":function(obj){
                var version = "6,0,21";
                try{
                    obj.AllowScriptAccess = "always";
                    version = getActiveXVersion(obj);
                }catch(err){}
                return version;
            }
        },
        {
            "name":"ShockwaveFlash.ShockwaveFlash",
            "version":function(obj){
                return getActiveXVersion(obj);
            }
        }
    ];
    /**
     * Extract the ActiveX version of the plugin.
     * 
     * @param {Object} The flash ActiveX object.
     * @type String
     */
    var getActiveXVersion = function(activeXObj){
        var version = -1;
        try{
            version = activeXObj.GetVariable("$version");
        }catch(err){}
        return version;
    };
    /**
     * Try and retrieve an ActiveX object having a specified name.
     * 
     * @param {String} name The ActiveX object name lookup.
     * @return One of ActiveX object or a simple object having an attribute of activeXError with a value of true.
     * @type Object
     */
    var getActiveXObject = function(name){
        var obj = -1;
        try{
            obj = new ActiveXObject(name);
        }catch(err){
            obj = {activeXError:true};
        }
        return obj;
    };
    /**
     * Parse an ActiveX $version string into an object.
     * 
     * @param {String} str The ActiveX Object GetVariable($version) return value. 
     * @return An object having raw, major, minor, revision and revisionStr attributes.
     * @type Object
     */
    var parseActiveXVersion = function(str){
        var versionArray = str.split(",");//replace with regex
        return {
            "raw":str,
            "major":parseInt(versionArray[0].split(" ")[1], 10),
            "minor":parseInt(versionArray[1], 10),
            "revision":parseInt(versionArray[2], 10),
            "revisionStr":versionArray[2]
        };
    };
    /**
     * Parse a standard enabledPlugin.description into an object.
     * 
     * @param {String} str The enabledPlugin.description value.
     * @return An object having raw, major, minor, revision and revisionStr attributes.
     * @type Object
     */
    var parseStandardVersion = function(str){
        var descParts = str.split(/ +/);
        var majorMinor = descParts[2].split(/\./);
        var revisionStr = descParts[3];
        return {
            "raw":str,
            "major":parseInt(majorMinor[0], 10),
            "minor":parseInt(majorMinor[1], 10), 
            "revisionStr":revisionStr,
            "revision":parseRevisionStrToInt(revisionStr)
        };
    };
    /**
     * Parse the plugin revision string into an integer.
     * 
     * @param {String} The revision in string format.
     * @type Number
     */
    var parseRevisionStrToInt = function(str){
        return parseInt(str.replace(/[a-zA-Z]/g, ""), 10) || self.revision;
    };
    /**
     * Is the major version greater than or equal to a specified version.
     * 
     * @param {Number} version The minimum required major version.
     * @type Boolean
     */
    self.majorAtLeast = function(version){
        return self.major >= version;
    };
    /**
     * Is the minor version greater than or equal to a specified version.
     * 
     * @param {Number} version The minimum required minor version.
     * @type Boolean
     */
    self.minorAtLeast = function(version){
        return self.minor >= version;
    };
    /**
     * Is the revision version greater than or equal to a specified version.
     * 
     * @param {Number} version The minimum required revision version.
     * @type Boolean
     */
    self.revisionAtLeast = function(version){
        return self.revision >= version;
    };
    /**
     * Is the version greater than or equal to a specified major, minor and revision.
     * 
     * @param {Number} major The minimum required major version.
     * @param {Number} (Optional) minor The minimum required minor version.
     * @param {Number} (Optional) revision The minimum required revision version.
     * @type Boolean
     */
    self.versionAtLeast = function(major){
        var properties = [self.major, self.minor, self.revision];
        var len = Math.min(properties.length, arguments.length);
        for(i=0; i<len; i++){
            if(properties[i]>=arguments[i]){
                if(i+1<len && properties[i]==arguments[i]){
                    continue;
                }else{
                    return true;
                }
            }else{
                return false;
            }
        }
    };
    /**
     * Constructor, sets raw, major, minor, revisionStr, revision and installed public properties.
     */
    self.FlashDetect = function(){
        if(navigator.plugins && navigator.plugins.length>0){
            var type = 'application/x-shockwave-flash';
            var mimeTypes = navigator.mimeTypes;
            if(mimeTypes && mimeTypes[type] && mimeTypes[type].enabledPlugin && mimeTypes[type].enabledPlugin.description){
                var version = mimeTypes[type].enabledPlugin.description;
                var versionObj = parseStandardVersion(version);
                self.raw = versionObj.raw;
                self.major = versionObj.major;
                self.minor = versionObj.minor; 
                self.revisionStr = versionObj.revisionStr;
                self.revision = versionObj.revision;
                self.installed = true;
            }
        }else if(navigator.appVersion.indexOf("Mac")==-1 && window.execScript){
            var version = -1;
            for(var i=0; i<activeXDetectRules.length && version==-1; i++){
                var obj = getActiveXObject(activeXDetectRules[i].name);
                if(!obj.activeXError){
                    self.installed = true;
                    version = activeXDetectRules[i].version(obj);
                    if(version!=-1){
                        var versionObj = parseActiveXVersion(version);
                        self.raw = versionObj.raw;
                        self.major = versionObj.major;
                        self.minor = versionObj.minor; 
                        self.revision = versionObj.revision;
                        self.revisionStr = versionObj.revisionStr;
                    }
                }
            }
        }
    }();
};
FlashDetect.JS_RELEASE = "1.0.4";



jQuery.fn.supersleight = function(settings) {
    settings = jQuery.extend({
        imgs: true,
        backgrounds: true,
        shim: '/assets/images/transparent.gif',
        apply_positioning: true
    }, settings);
    return this.each(function(){
        if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7 && parseInt(jQuery.browser.version, 10) > 4) {
            jQuery(this).find('*').andSelf().each(function(i,obj) {
                var self = jQuery(obj);
                // background pngs
                if (settings.backgrounds && self.css('background-image').match(/\.png/i) !== null) {
                    var bg = self.css('background-image');
                    var src = bg.substring(5,bg.length-2);
                    var mode = (self.css('background-repeat') == 'no-repeat' ? 'crop' : 'scale');
                    var styles = {
                        'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')",
                        'background-image': 'url('+settings.shim+')'
                    };
                    self.css(styles);
                };
                // image elements
                if (settings.imgs && self.is('img[src$=png]')){
                    var styles = {
                        'width': self.width() + 'px',
                        'height': self.height() + 'px',
                        'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + self.attr('src') + "', sizingMethod='scale')"
                    };
                    self.css(styles).attr('src', settings.shim);
                };
                // apply position to 'active' elements
                if (settings.apply_positioning && self.is('a, input') && (self.css('position') === '' || self.css('position') == 'static')){
                    self.css('position', 'relative');
                };
            });
        };
    });
};


var flash_video_c = 0;
var flash_video_volume_initial = 100;

function flash_video_add(sel, flv, img) {
    $el = $(sel);
    $el.append('<div class="flash-container"></div>');
    $div = $('<div class="flash-video-overlay"></div>').appendTo($el);
    $img = $('<img src="/assets/images/btn-play.png">').appendTo($div); 
    $img.supersleight();
    $image_overlay = $('<div class="flash-player-controls"></div>').appendTo($el);
 
    add_player_controls($image_overlay);

    if (img)
    {
        $image_overlay.css('background-image', 'url("' + img + '")');
    }
 
    var width  = parseInt($el.css('width'));
    var height = parseInt($el.css('height'));

    $('.flash-container', $el).flash({
        swf: '/assets/flash/swfobject/carousel-swfObj.swf',
        width: width,
        height: height,
        allowFullScreen: true,
        allowScriptAccess: 'always',

        flashvars: {
            videocontent: flv,
            allowFullScreen: true,
            allowScriptAccess: 'always',
            width: 360,
            height: 270
        }
    });
    flash_video_buffer(sel);
};

function flash_video_remove()
{
    $('.flash-container').flash().remove();
}

function flash_video_insert(sel, url, img)
{
    flash_video_add(sel, url, img);

    /*
    $(".volume", sel).slider({
        value: flash_video_volume_initial,
        slide: function(event, ui)
        {
            SliderVolume($(this).data('id'));
        }
    });
    */

    $('.flash-video-overlay', sel).click(function() {
        if (flash_video_playing)
        {
            $(this).addClass('flash-video-overlay-cover');
            flash_video_pause(sel);
            var flashObj = $('.flash-container object', sel)[0];
            flashObj.getSizeNow();
            $(this).next('.flash-player-controls').fadeIn('slow').addClass("flash-player-controls-active");
        }
        else
        {
            // Initial play
            var flashObj = $('.flash-container object', sel)[0];
            flashObj.getSizeNow();
            flash_video_playing = true;

            // Remove the initial 'play' button
            $('img', this).remove();
            var flashObj = $('.flash-container object', sel)[0];
            var time = flashObj.PlayerTime();
            $(this).next('.flash-player-controls').css('background-image', '');

            $(this).next('.flash-player-controls').fadeOut('slow', function() {
                flash_video_buffer_seek(sel, "0");
                flash_video_buffer_play(sel);
            });
        }
    });
}

function add_player_controls($el)
{
    // console.log("add_player_controls", $el);
    var sel = '#' + $el.parent()[0].id;
    $el.html('').append('<img id="btn-play" src="/assets/images/btn-play.png"><img id="btn-restart" src="/assets/images/btn-restart.png">');

    $("#btn-play", $el).click(function() {
        flash_video_playing = true;

        $(this).parents('.flash-player-controls').fadeOut('slow', function() {
            $(this).parents('.flash-player-holder').find('.flash-video-overlay-cover').removeClass('flash-video-overlay-cover');
             flash_video_buffer_play(sel);
        });

        return false;
    });

    $("#btn-restart", $el).click(function() {
        flash_video_playing = true;

        $(this).parents('.flash-player-controls').fadeOut('slow', function() {
            $(this).parents('.flash-player-holder').find('.flash-video-overlay-cover').removeClass('flash-video-overlay-cover');
            flash_video_buffer_seek(sel, "0");
            flash_video_buffer_play(sel);
        });

        return false;
    });
}

function flash_video_buffer_seek(sel, pos)
{
    var flashObj = $(".flash-container object", sel);

    if (!flashObj.length)
    {
        setTimeout("flash_video_buffer_seek('" + sel + "', " + pos + ")", 100);
    }
    else
    {
        flashObj = flashObj[0];

        if (!flashObj.Seeker)
        {
            setTimeout("flash_video_buffer_seek('" + sel + "', " + pos + ")", 100);
        }
        else
        {
            flashObj.Seeker(pos);
        }
    }
}

function flash_video_buffer(sel)
{
    /*
    flash_video_c++;
    if (flash_video_c > 1000)
    {
        return;
    }
    */

    var flashObj = $(".flash-container object", sel);

    if (!flashObj.length)
    {
        setTimeout("flash_video_buffer('" + sel + "')", 1000);
    }
    else
    {
        flashObj = flashObj[0];

        if (!flashObj.PlayerVolume)
        {
            setTimeout("flash_video_buffer('" + sel + "')", 1000);
        }
        else
        {
            flash_video_volume(sel, flash_video_volume_initial);
        }
    }
}

function flash_video_buffer_play(id)
{
    flash_video_playing = true;
    var $fph = $(id);
    var flashObj = $('object', $fph)[0];
 
    if (flashObj.getDuration)
    {
        var duration = flashObj.getDuration();

        if (duration == 0)
        {
            setTimeout("flash_video_buffer_play('" + id + "')", 100);
        }
        else
        {
            flash_video_play(id);
        }
    }
    else
    {
        flash_video_play(id);
    }
}

function flash_video_play(id)
{
    var flashObj = $('.flash-container object', id)[0];
    flashObj.playFunction();
    $('.play-toggle', id).attr('value', "Pause");
}

function flash_video_pause(id)
{
    var $fph = $(id);
    var flashObj = $('object', $fph)[0];
 
    if (flashObj.PlayerTime)
    {
        $(id).data('video_time', flashObj.PlayerTime());
    }
 
    var flashObj = $('.flash-container object', id)[0];
    flashObj.pauseFunction();
    $('.play-toggle', id).attr('value', "Play");
    flash_video_playing = false;
}

function flash_video_volume(id, amount)
{
    var flashObj = $('.flash-container object', id)[0];
    flashObj.PlayerVolume(amount / 100);
}

function init_flash_videos()
{
    if (FlashDetect.installed)
    {
        $('.flash-player-holder').each(function() {
            var url = $('.video_url', this).attr('href');

            if (url)
            {
                var img = $('img', this).attr('src');
                $('a', this).remove();
                flash_video_insert('#' + this.id, url, img);
            }
        });
    }
}







//-----------------------------------------------------------------------------
// postcode-anywhere.js - 14739
// Add postcode anywhere support to a form
//-----------------------------------------------------------------------------
function pa_postcode_building(Key, Postcode, Building, UserName)
{
    var scriptTag = document.getElementById("PCAddfa549d54b84549b8098d0d32f1c6a1");
    var headTag = document.getElementsByTagName("head").item(0);
    var strUrl = "";

    // Build the url
    strUrl = "https://services.postcodeanywhere.co.uk/PostcodeAnywhere/Interactive/RetrieveByPostcodeAndBuilding/v1.10/json.ws?";
    strUrl += "&Key=" + escape(Key);
    strUrl += "&Postcode=" + escape(Postcode);
    strUrl += "&Building=" + escape(Building);
    strUrl += "&UserName=" + escape(UserName);
    strUrl += "&CallbackFunction=got_postcode";

    // Make the request
    if (scriptTag)
    {
        try
        {
            headTag.removeChild(scriptTag);
        }
        catch (e)
        {
            // Ignore
        }
    }
 
    scriptTag = document.createElement("script");
    scriptTag.src = strUrl
    scriptTag.type = "text/javascript";
    scriptTag.id = "PCAddfa549d54b84549b8098d0d32f1c6a1";
    headTag.appendChild(scriptTag);
}

function got_postcode(response)
{
    // Test for an error
    if (response.length == 1 && typeof(response[0].Error) != 'undefined')
    {
        // If an error occurs (i.e. we're out of credit) ...
        $('#results').html('');
        output_address({ Line1: '', PostTown: '', Postcode: '' });
    }
    else
    {
        handle_addresses(response);
    }
}

function handle_addresses(addresses)
{
    $('#results').html('');

    // Check if there were any items found
    if (addresses.length == 0)
    {
        alert("Sorry, no matching items found");
    }
    else if (addresses.length > 1)
    {
        $('#results').append('<p style="padding-top: 1em; font-style: italic;">Several address matched. Please select your address from the list below:</p>');

        if (addresses.length < 10)
        {
        }

        html = '';

        html += '<p class="control-h">';
        html += '<label for="choose">Choose ...</label>';

        var addr_buffer = {};
        var options = '';
        num_opts = '';

        for (r in addresses)
        {
            var address = addresses[r];
            var lines = [];

            for (i = 1; i <= 5; i++)
            {
                if (!address['Line' + i])
                {
                    break;
                }

                lines[lines.length] = address['Line' + i];
            }

            var addr = lines.join(', ');

            if (!addr_buffer.hasOwnProperty(addr))
            {
                addr_buffer[addr] = '';
                options += '<option value="' + r + '">' + lines.join(', ') + '</option>';
                num_opts++;
            }
        }

        html += '<select style="margin-bottom: 20px;" id="choose" size="' + num_opts + '">';
        html += options;
        html += '</select></p>';

        $('#results').append(html);
     
        $('#choose').change(function() {
            $('#final').remove();
            var v = $(this).val();

            if (v)
            {
                output_address(addresses[v], true);
                $('#results').html('');
            }
        });
    }
    else
    {
        output_address(addresses[0], true);
    }
}

function output_address(addr, found)
{
    if (found)
    {
        $('#please-check').show();
    }
    else
    {
        $('#not-found').show();
    }

    var line = addr['Line1'];
    var addr2 = '';

    if (addr['Line2'])
    {
        addr2 = addr['Line2'];
    }

    $('#address1').val(addr['Line1']);
    $('#address2').val(addr['Line2']);
    $('#address3').val(addr['Line3']);
    $('#address4').val(addr['Line4']);

    $('#town').val(addr['PostTown']);
    $('#postcode').val(addr['Postcode']);

    if (addr.CountryName == 'England' || addr.CountryName == 'Wales' || addr.CountryName == 'Scotland' || addr.CountryName == 'Northern Ireland')
    {
        $sel = $('select#country option[value="UK"]');
        $sel.attr('selected', 'selected');
    }

    $('#address-details').show();
}

function init_postcode_anywhere()
{
    $('#standard').append('<input type="hidden" name="address3" id="address3">');
    $('#standard').append('<input type="hidden" name="address4" id="address4">');
    $('#address-details').before('<div id="results"></div>'); //.hide();

    $('#results').before('<p class="control-h"><label for="building" style="margin-top: 2em">Building number/name</label><input id="building" type="text" style="margin-top: 2em"></p>');

    $('#results').before('<p class="control-h"><label for="postcode-lookup">Postcode</label><input id="postcode-lookup" type="text"></p>');

    $('#results').before('<p class="control-h"><input id="btn" class="lookup-button" style="width: auto;" type="submit" value="Look up address details …"></p>');

    var check = '<p id="please-check" class="msg" style="font-style: italic; padding-top: 1em; clear: both;">Please check your address carefully and amend if required</p>';

    $(check).insertBefore('#address-details').hide();

    var not_found = '<p id="not-found" class="msg" style="font-style: italic; padding-top: 1em; clear: both;">Your address details could not be located. Please complete your address below:</p>';
    $(not_found).insertBefore('#address-details').hide();

    $('#standard #btn').click(function() {
        $('#address-details,.msg').hide();

        var building = $('#building').val();
        var postcode = $('#postcode-lookup').val();

        if (!postcode)
        {
            alert('Please enter a postcode!');
        }
        else
        {
            lookup(postcode, building);
        }

        return false;
    });
}

function lookup(postcode, building)
{
    postcode = postcode.replace(/\s/g, '');
    var key = 'XB43-JE51-UT98-DH69';
    var username = '';
    pa_postcode_building(key, postcode, building, username);
}

//-----------------------------------------------------------------------------
// [290] - homepage carousel fancybox func 15491 - 15491
// homepage carousel video class for launching iframed youtube video
//-----------------------------------------------------------------------------
function carousel_popup()
{
    $(".homepageCarouselVideo").fancybox({
        'width' : 640,
        'height' : 390,
        'autoScale' : false,
        'transitionIn' : 'fade',
        'transitionOut' : 'none',
        'type' : 'iframe',
        'overlayOpacity' : 0.7,
        'overlayColor' : '#000'
    });
}

//-----------------------------------------------------------------------------
// [290] - jqueryswfobject flash embed - 15765
// Gavi countdown clock for carousel
//-----------------------------------------------------------------------------
function flash_countdown()
{
    $('#myFlashHome').flash({
        swf: 'http://www.savethechildren.org.uk/assets/flash/countdown/countDown-carousel.swf',
        width: 360,
        height: 270
    });
}

//-----------------------------------------------------------------------------
// [290] - healthworkers progress thermometer - 16252 - 16252
// Updates number of 'healthworkers' actions and animates progress 'thermometer'
//-----------------------------------------------------------------------------
function healthworkers_progress()
 {
    $hwprogress = $('.healthworkers-progress');

    if ($hwprogress.length)
    {
        $.get('/assets/xml/healthworkers.xml', function(xml) {
            var currentAmount = parseInt($(xml).find('total').text());
            $.getJSON('/assets/json/healthworker.json', function(data) {
                var itemNum = data.pages[0].form.fields[0].value;
                var found = itemNum.match(/^[^0-9]*([0-9]+)/);
                var total = parseInt(found[1]) + currentAmount;
                total = String(total).replace(/^\d+(?=.|$)/, function (int) { return int.replace(/(?=(?:\d{3})+$)(?!^)/g, ","); });

                var target = 60000;
                var base_height = 75;
                var height = (currentAmount / target) * 171;

                $('.currentAmount').text(total);

                $('.healthworkers-progress .bar').animate({ height: base_height + height + 'px' }, 4000);
            });
        }, 'xml');
    }
}

var local_campaigner_events = [

        {
                name: "Annual campaigns conference",
                intro: "Would you like to get more involved with Save the Children’s campaigns? Interested in current affairs and ensuring politicians keep to their promises? Then we’ve got just the event for you! ",
                location: "",
                date: '2011-11-26',
                link: '/en/our-campaigners_16514.htm'
        },{
                name: "LSE Freshers' Fair",
                intro: "",
                location: "",
                date: '2011-09-29',
                link: '/en/our-campaigners_16498.htm'
        },{
                name: "Sheffield Hallom Freshers' Fair",
                intro: "",
                location: "",
                date: '2011-09-23',
                link: '/en/our-campaigners_16501.htm'
        },{
                name: "UAL Freshers' Fair",
                intro: "",
                location: "",
                date: '2011-09-28',
                link: '/en/our-campaigners_16499.htm'
        },{
                name: "Empowering women, saving children's lives",
                intro: "Save the Children will host 'Empowering women, saving children’s lives’ at the Labour Party Conference (outside secure zones)",
                location: "",
                date: '2011-09-27',
                link: '/en/our-campaigners_16495.htm'
        },{
                name: "Empowering women, saving children's lives",
                intro: "Save the Children (with the Conservative Women’s Organisation) will host ‘Empowering women, saving children’s lives’ at the Conservative Party Conference (outside secure zones).",
                location: "",
                date: '2011-10-04',
                link: '/en/our-campaigners_16494.htm'
        },{
                name: "Latest news from the UN summit",
                intro: "The UN Summit will be taking place in New York and will be the pinnacle event that our health workers campaign has been leading up to.",
                location: "",
                date: '2011-09-19',
                link: '/en/our-campaigners_16330.htm'
        },{
                name: "Blogging conference: register today",
                intro: "Hear from the experts, learn new skills and find new ways to really write with impact.",
                location: "",
                date: '2011-09-17',
                link: '/en/our-campaigners_16329.htm'
        },{
                name: "First Talk Action Teleconference",
                intro: "Join our first Talk Action teleconference series on Wednesday 14th September 19:00 – 20:00 where we will be asking our panel of experts ‘Why it’s Time to End the Global Health Worker Shortage’.",
                location: "",
                date: '2011-09-14',
                link: '/en/our-campaigners_16328.htm'
        },

        {}
];//-----------------------------------------------------------------------------
// local-campaigners-events.js - 16287
//-----------------------------------------------------------------------------
local_campaigner_events.pop();

local_campaigner_events = local_campaigner_events.sort(function(a, b) {
    if (a.date > b.date) return 1;
    if (a.date < b.date) return -1;
    return 0;
});

function event_calendar(cal, events, url_part)
{
    $(cal).datepicker({
        minDate: fromISODate(events[0].date),
        maxDate: fromISODate(events[events.length - 1].date),

        beforeShowDay: function(theDate) {
            var iDate = toISODate(theDate);

            for (d in events)
                if (events[d].date == iDate)
                    return [ true ];

            return [ false ];
        },

        dateFormat: 'yy-mm-dd',

        onSelect: function(dateText, inst)  {

            // Redirect to the appropriate month#day page. A server-side
            // redirect (one per year) handles this.

            var year   = dateText.substr(0, 4);
            var month  = dateText.substr(5, 2);
            var day    = dateText.substr(8, 2);

            var base = 'http://www.savethechildren.org.uk/' + url_part + '/';

            window.location = base + year + '/' + month + '/' + day;
        }
    });
}

function init_calendars()
{
    $('.calendar').each(function() {
        switch (this.id)
        {
            case 'lceventcalendar':
                event_calendar(this, local_campaigner_events, 'lcevents');

                var evs = local_campaigner_events
                    .sort(function(a, b) {
                        if (a.date > b.date) return -1;
                        if (a.date < b.date) return 1;
                        return 0;
                    })
                    .slice(0, 3)
                    .sort(function(a, b) {
                        if (a.date > b.date) return 1;
                        if (a.date < b.date) return -1;
                        return 0;
                    });

                var now_date = new Date();

                for (var e in evs)
                {
                    var name = '<a href="' + evs[e].link + '">' + evs[e].name + '</a>';
                    var date_parts = evs[e].date.split("-");
                    var date = '';

                    if (date_parts.length == 3)
                    {
                        var d = new Date(date_parts[0], date_parts[1] - 1, date_parts[2]);

                        if (d < now_date)
                            continue;

                        date = '<span class="date">' + to_stc_date(d) + '</span>';
                    }

                    $('#lcupevents').append('<li>' + name + ' ' + date + '</li>');
                }

                if ($('#lcupevents li').length == 0)
                {
                    $('#lcupevents').prev('h2').remove();
                    $('#lcupevents').remove();
                }

                break;

            /*case 'eventcalendar':
                event_calendar(this, other_events, 'events');
                break;*/
        }
    });
}var local_campaigner_groups = [
    {
    marker: {
    lat: '51.4991',
    lng: '-0.0917',
    title: "Save the Children Camberwell and Peckham Campaigns",
    url: "http://www.facebook.com/groups/210822598963654?ap=1",
    description: ""
},
    type: 'local',
    name: "Camberwell & Peckham"
},{
    marker: {
    lat: '53.5253',
    lng: '-1.1314',
    title: "Save the Children Doncaster North Campaigns",
    url: "http://www.facebook.com/groups/187109644682364?ap=1",
    description: ""
},
    type: 'local',
    name: "Doncaster North"
},{
    marker: {
    lat: '51.5031',
    lng: '-0.1777',
    title: "Imperial College London",
    url: "",
    description: ""
},
    type: 'university',
    name: ""
},{
    marker: {
    lat: '51.51104',
    lng: '-0.11699',
    title: "Kings College London",
    url: "",
    description: ""
},
    type: 'university',
    name: ""
},{
    marker: {
    lat: '51.51473',
    lng: '-0.11564',
    title: "London School of Economics (LSE)",
    url: "",
    description: ""
},
    type: '',
    name: ""
},{
    marker: {
    lat: '53.3797',
    lng: '-1.4714',
    title: "Save the Children Sheffield Campaigns",
    url: "http://www.facebook.com/groups/187300047997234?ap=1",
    description: ""
},
    type: 'local',
    name: "Sheffield"
},{
    marker: {
    lat: '51.43772',
    lng: '-0.33539',
    title: "St. Mary's University",
    url: "",
    description: ""
},
    type: 'university',
    name: ""
},{
    marker: {
    lat: '51.4504',
    lng: '-0.1209',
    title: "Save the Children Streatham Campaigns",
    url: "http://www.facebook.com/groups/215579745158446/",
    description: ""
},
    type: 'local',
    name: "Streatham"
},{
    marker: {
    lat: '52.4809',
    lng: '-1.9106',
    title: "Save the Children Sutton Coldfield Campaigns",
    url: "http://www.facebook.com/groups/179599808777463/",
    description: ""
},
    type: 'local',
    name: "Sutton Coldfield"
},{
    marker: {
    lat: '',
    lng: '',
    title: "Save the Children Tatton Campaigns",
    url: "http://www.facebook.com/groups/255253534488115?ap=1",
    description: ""
},
    type: 'local',
    name: "Tatton"
},{
    marker: {
    lat: '51.48377',
    lng: '-0.00505',
    title: "University of Greenwich",
    url: "",
    description: ""
},
    type: 'university',
    name: "University of Greenwich"
},{
    marker: {
    lat: '51.51712',
    lng: '-0.14330',
    title: "University of Westminster",
    url: "",
    description: ""
},
    type: 'university',
    name: ""
},{
    marker: {
    lat: '51.7391',
    lng: '-1.279',
    title: "Save the Children Witney Campaigns",
    url: "http://www.facebook.com/groups/120865724674418?ap=1",
    description: ""
},
    type: 'local',
    name: "Witney"
},{
    marker: {
    lat: '51.5002',
    lng: '-0.1430',
    title: "Youth Campaigner Battersea",
    url: "",
    description: ""
},
    type: 'youth',
    name: ""
},{
    marker: {
    lat: '51.5155',
    lng: '-0.0886',
    title: "Youth Campaigner Holborn",
    url: "",
    description: ""
},
    type: 'youth',
    name: ""
},{
    marker: {
    lat: '52.6333',
    lng: '1.300',
    title: "Youth Campaigner Norwich",
    url: "",
    description: ""
},
    type: 'youth',
    name: ""
},{
    marker: {
    lat: '51.456',
    lng: '-0.113',
    title: "Youth Campaigner Streatham",
    url: "",
    description: ""
},
    type: 'youth',
    name: ""
},
    {}
];//-----------------------------------------------------------------------------
// local-campaigners.js - 16276
//-----------------------------------------------------------------------------
function local_campaigners_map()
{
    var preston = new google.maps.LatLng(53.757729, -2.70344);
    var mapZoom = 6;

    var window_opts = {
        maxWidth: 300
    };

    var lc_info_window = new google.maps.InfoWindow(window_opts);

    var myOptions = {
        zoom: mapZoom,
        center: preston,
        minZoom: 6,
        maxZoom: 11,
        streetViewControl: false,
        panControl: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var local_campaigners_map = new google.maps.Map(document.getElementById("map"), myOptions);

    for (var m in local_campaigner_groups)
    {
        var group = local_campaigner_groups[m];
        var marker = group.marker;

        if (!marker || !marker.lat || !marker.lng)
        {
            continue;
        }

        var point = new google.maps.LatLng(marker.lat, marker.lng);
        var title = marker.title ? marker.title : 'test';

        var gmarker = new google.maps.Marker({
            position: point,
            title: title
        });

        gmarker.setMap(local_campaigners_map);

        var content = marker.title ? marker.title : '';

        if (marker.url)
        {
            content = '<a href="' + marker.url + '">' + content + '</a>';
        }

        content = '<h2>' + content + '</h2>';

        switch (group.type)
        {
            case 'local':
                if (marker.url)
                {
                    content += '<p>To find out about the local campaigning in ' + group.name + ' visit <a href="' + marker.url + '">' + marker.url + '</a></p>';
                }
                else
                {
                    content += '<p>To find out more about the local campaigning in ' + group.name + ' please contact <a href="mailto:campaigngroups@savethechildren.org.uk">campaigngroups@savethechildren.org.uk</a> or call 020 7012 6400 and speak to the campaigns team about becoming more active in your area.</p>';
                }

                break;

            case 'university':
                content += '<p>To find out about joining the ' + group.name + ' student group, please email <a href="mailto:campaigngroups@savethechildren.org.uk">campaigngroups@savethechildren.org.uk</a> who will put you in touch with the lead campaigner. If you are interested in setting up a Save the Children student group, get in touch and we can provide materials, training and guidance on getting you started.</p>';
                break;

            case 'youth':
                content += '<p>To become one of our youth campaigners please contact <a href="mailto:campaigns@savethechildren.org.uk">campaigns@savethechildren.org.uk</a> or call 020 7012 6400 and speak to one of the campaigns team. We work with lots of young people in various ways and would welcome new youth campaigners to our network. We are also able to provide training.</p>';
                break;

            case 'leaders':
                content += '<p>To contact one of our team leaders and find out what is happening in ' + group.name + ' please contact <a href="mailto:campaigngroups@savethechildren.org.uk">campaigngroups@savethechildren.org.uk</a> who will put you in touch with the representative. If you would like to become one of our team leaders and lead campaigns in your local area, get in touch and we can provide materials, training and guidance on getting you started.</p>';
        }

        //content += marker.description ? marker.description : "test content";

        add_google_map_marker(local_campaigners_map, gmarker, lc_info_window, content);
    }
}

function add_google_map_marker(map, marker, info_window, content)
{
    google.maps.event.addListener(marker, 'click', function() {
        info_window.setContent(content);
        info_window.setPosition(this.getPosition());
        info_window.open(map, this);
    });
}

