/**
 * @author simon
 * 
 * Use Module Pattern: http://yuiblog.com/blog/2007/06/12/module-pattern/
 */

var BRC = function($) {
	
	// Private methods and properties

	var countdown_timeout;

	var countdown = function(days, hours, minutes, seconds) {
		seconds = (seconds == 0) ? 59 : seconds-1;
		$('#countdown .seconds span').text(seconds);
		if (seconds == 59) {
			minutes = (minutes == 0) ? 59 : minutes-1;
			$('#countdown .minutes span').text(minutes);
			if (minutes == 59) {
				hours = (hours == 0) ? 23 : hours-1;
				$('#countdown .hours span').text(hours);
				if (hours == 23) {
					days = days-1;
					if (days < 0) {
						$('#countdown').html('NOW!');
						countdown_timeout = null;
						return;
					} else {
						$('#countdown .days span').text(days);
					}
				}
			}
		}
		
		countdown_timeout = setTimeout(function() {countdown(days, hours, minutes, seconds);}, 1000);
	}
	
	// Public methods and properties
	return {
		init : function() {


			// Menu
			$('#main-navigation li').hover(
				function(){
					$(this).addClass('hover');
					$sub = $('#main-navigation ul:visible');
					$body = $('#body');
					if ($sub.offset().left + $sub.width() > $body.offset().left + $body.width()) {
						$sub.css({left: 'auto', right: '0'});
					}

					$subsub = $('#main-navigation ul ul:visible');
					if ($subsub.offset().left + $subsub.width() > $body.offset().left + $body.width()) {
						$subsub.css({left: '-170px'});
					}
				},
				function(){
					$(this).removeClass('hover');
				}
			);

			// Make labels hover in subscribe box.
			$('#subscribe-box span.field').css({
				'display': 'block',
				'position': 'relative', 
				'margin-bottom': '5px'
			});

			// Countdown
			if ($('#countdown').length > 0) {
				var now = new Date();
				var date = new Date($('#countdown').text());

				var diff = date.getTime() - now.getTime();

				var seconds = Math.floor(diff/1000);
				var minutes = Math.floor(seconds/60);
				seconds = seconds % 60;
				var hours = Math.floor(minutes/60);
				minutes = minutes % 60;
				var days = Math.floor(hours/24);
				hours = hours % 24;

				$('#countdown').html('<span class="days"><span>' + days + '</span> days</span> <span class="hours"><span>' + hours + '</span> hours</span> <span class="minutes"><span>' + minutes + '</span> minutes</span> <span class="seconds"><span>' + seconds + '</span> seconds</span> ').show();

				countdown(days, hours, minutes, seconds);

			}

			// Tabify
			$('#nwa').tabs();
			
			$('#subscribe-box span.field label').css({'position': 'absolute', 'top': '4px', 'left': '3px', 'color': '#ccc'});
			
			$('#subscribe-box span.field input[type="text"]')
				.focus(function(){
					var id = $(this).attr('id');
					$('label[for='+id+']').hide();
				})
				.blur(function(){
					var $this = $(this);
					if ($this.val() == '') {
						var id = $this.attr('id');
						$('label[for='+id+']').show();
					}
				})
				.each(function() {
					var $this = $(this);
					var id = $this.attr('id');
					if ($this.val() == '') {
						$('label[for='+id+']').show();
					} else {
						$('label[for='+id+']').hide();
					}
				});
			

			// Load the weather
			$.getJSON("http://www.worldweatheronline.com/feed/weather.ashx?lat=-27.428652&lon=153.073282&format=json&num_of_days=2&key=2af2705bdc031433100605&callback=?", function(data, textStatus) {
				$('#weather img').attr('src', '/themes/brc/images/weather/' + data.data.weather[0].weatherCode + '.png').attr('alt', data.data.weather[0].tempMaxC + "° " + data.data.weather[0].weatherDesc[0].value);
				$('#weather span').text(data.data.weather[0].tempMaxC + "° " + data.data.weather[0].weatherDesc[0].value).attr('title', data.data.weather[0].tempMaxC + "° " + data.data.weather[0].weatherDesc[0].value);
			});


			// Carousel
			$('#featured-events-carousel').jcarousel({
				visible : 1,
				scroll : 1,
				wrap : 'both',
				initCallback: BRC.init_carousel,
				buttonNextHTML: null,
				buttonPrevHTML: null,
				auto: 4
			});

			// Add lightbox stuff for gallery pages.

			$('.gallery-image.lightbox').lightBox({
				imageLoading: '/themes/brc/images/lightbox-ico-loading.gif',
				imageBtnClose: '/themes/brc/images/lightbox-btn-close.gif',
				imageBtnPrev: '/themes/brc/images/lightbox-btn-prev.gif',
				imageBtnNext: '/themes/brc/images/lightbox-btn-next.gif'
			});
			$('.venue-map-link').lightBox({
				imageLoading: '/themes/brc/images/lightbox-ico-loading.gif',
				imageBtnClose: '/themes/brc/images/lightbox-btn-close.gif',
				imageBtnPrev: '/themes/brc/images/lightbox-btn-prev.gif',
				imageBtnNext: '/themes/brc/images/lightbox-btn-next.gif'
			});
			/*
			if ($('.gallery-image').length > 0) {
				$.getScript('/themes/brc/js/jquery.lightbox.js', function(){
					
				});	
			}
			
			// Add lightbox for venue maps
			if ($('.venue-map-link').length > 0) {
				$.getScript('/themes/brc/js/jquery.lightbox.js', function() {
					$('.venue-map-link').lightBox();
				});
			}
			*/
			if ($('#featured-event-container')) {
				$('.featured-event-summary').fadeTo(0, 0);
				$('#featured-event-container .event').hover ( function(event) {
					$('.featured-event-summary', this).stop().css({padding :'10px'}).fadeTo('fast', 0.8);
				},
				function (event) {
					$('.featured-event-summary', this).stop().fadeTo('fast', 0);
				});
					
			}
			
			$('tbody>tr:odd').addClass('alt');


			// Setup the tracking
			$('#logo-link').track({
				category : 'link',
				action: function(element) {return element.attr('href').replace('http://www.brc.com.au', '')},
				label : 'logo',
				skip_internal : false
			});

			$('#header a').track({
				category : 'link',
				action: function(element) {return element.attr('href').replace('http://www.brc.com.au', '')},
				label : 'header',
				skip_internal : false
			});

			$('#main-navigation a').track({
				category : 'link',
				action: function(element) {return element.attr('href').replace('http://www.brc.com.au', '')},
				label : 'main-navigation',
				skip_internal : false
			});

			$('#sidebar a').track({
				category : 'link',
				action: function(element) {return element.attr('href').replace('http://www.brc.com.au', '')},
				label : 'sidebar',
				skip_internal : false
			});

			$('#footer a').track({
				category : 'link',
				action: function(element) {return element.attr('href').replace('http://www.brc.com.au', '')},
				label : 'footer',
				skip_internal : false
			});

			$('#content a').track({
				category : 'link',
				action: function(element) {return element.attr('href').replace('http://www.brc.com.au', '')},
				label : 'content',
				skip_internal : false
			});

			$('a').track({
				category : 'link',
				action: function(element) {return element.attr('href').replace('http://www.brc.com.au', '')},
				label : 'other',
				skip_internal : false
			});
		},
		
		menu_panel : {
			
			current : '',
			
			timer :'',
			
			show : function (element) {
				// Close all open dropbuttons
				$('#navigation>li').removeClass('hover').removeClass('fade');
		
				// Open this drop button
				$(BRC.menu_panel.current).addClass('hover');
				$('#navigation>li:not(.hover)').addClass('fade');
				$('#breadcrumb').css({'visibility':'hidden'}); /* Stops Cufon text poking through menu */
			},
			
			hide : function (element) {
				// Fade out and close dropbutton
				$(BRC.menu_panel.current).removeClass('hover');
				$('#navigation>li').removeClass('fade');
				$('#breadcrumb').css({'visibility':''}); 
			}
		},
		
		init_carousel : function (carousel) {
			
			if ($('#featured-events-carousel li').length > 1) {
				$('#carousel-controls .next').bind('click', function() {
			        carousel.next();
					carousel.startAuto(0);
			        return false;
			    });
			
			    $('#carousel-controls .prev').bind('click', function() {
			        carousel.prev();
					carousel.startAuto(0);
			        return false;
			    });
				
				$('#carousel-controls').slideDown();
				
				carousel.clip.hover(function() {
			        carousel.stopAuto();
			    }, function() {
			        carousel.startAuto();
			    });
				
			}
			
			$('#featured-events-carousel').css({
				'display': 'block',
				'visibility': 'visible'
			});
		}
	}
	
}(jQuery);

/**
 * @author Alexander Farkas
 * v. 1.1
 */

(function($){
	
	if(!document.defaultView || !document.defaultView.getComputedStyle){
		var oldCurCSS = jQuery.curCSS;
		jQuery.curCSS = function(elem, name, force){
			if(name !== 'backgroundPosition' || !elem.currentStyle || elem.currentStyle[ name ]){
				return oldCurCSS.apply(this, arguments);
			}
			var style = elem.style;
			if ( !force && style && style[ name ] ){
				return style[ name ];
			}
			return oldCurCSS(elem, 'backgroundPositionX', force) +' '+ oldCurCSS(elem, 'backgroundPositionY', force);
		};
	}
})(jQuery);

(function($) {
	
	function toArray(strg){
		strg = strg.replace(/left|top/g,'0px');
		strg = strg.replace(/right|bottom/g,'100%');
		strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
		var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
		return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
	}
	
	$.fx.step. backgroundPosition = function(fx) {
		if (!fx.bgPosReady) {
			
			var start = $.curCSS(fx.elem,'backgroundPosition');
			if(!start){//FF2 no inline-style fallback
				start = '0px 0px';
			}
			
			start = toArray(start);
			fx.start = [start[0],start[2]];
			
			var end = toArray(fx.options.curAnim.backgroundPosition);
			fx.end = [end[0],end[2]];
			
			fx.unit = [end[1],end[3]];
			fx.bgPosReady = true;
		}
		
		var nowPosX = [];
		nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
		nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];           
		fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];

	};
})(jQuery);


/**
 * Cookie plugin
 *
 * Copyright (c) 2006 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
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};