// create our namespace

var BGC = BGC || {};

BGC.config = {
	firebugURL: "http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js",
	
	gaURL: (("https:" == document.location.protocol) ? "https://ssl." : "http://www.") + "google-analytics.com/ga.js",
	
	debug: false
};

$(function () {
	BGC.isIE = $.browser.msie;
	
	// animate button hover states
	$("a.crossfade").hover(function () {
		if (!BGC.isIE) {
			$(this).stop().fadeTo(300, 0);
		} else {
			$(this).css("opacity", 0);
		}
	}, function () {
		if (!BGC.isIE) {
			$(this).stop().fadeTo(600, 1);
		} else {
			$(this).css("opacity", 1);
		}
	});
});

// console logging (loads firebug lite if needed)
		
BGC.log = function () {
	if (BGC.config.debug || window.location.hash.match(/debug/i)) {
		try {
			if (typeof loadFirebugConsole === "function" && typeof console === "undefined") {
				window.loadFirebugConsole();
			}
			console.log.apply(this, arguments);
		} catch (err) {
			BGC.log._arg.push(arguments);
			if (!BGC.loadscript[BGC.config.firebugURL]) {
				BGC.loadscript(BGC.config.firebugURL, function () {
					try {
						var a;
						firebug.init();
						while (a = BGC.log._arg.shift()) {
							BGC.log(a);
						}
					} catch (err) {}
				});
			}
		}
	}
};

BGC.log._arg = [];

// google analytics tracking

BGC.track = function (str, callback) {
	try {
		var url = BGC.config.gaURL;
		//url += "?nocache=" + new Date(); // force it load over the wire for testing
		//url = "badurl.js"; // for testing tracking script load error
		
		if (str !== "IGNORE") { // prevents duplicate tracking calls when the loadscript callback is fired
			BGC.track._trackingstrings.push({
				str: str,
				callback: callback
			});
			BGC.log(BGC.track._trackingstrings);
		}
		
		if (typeof _gat === "undefined" && !BGC.track._abort) { // need to load our own copy of the GA script
			switch (BGC.loadscript[url]) {
				case "complete": // if we wind up here, the GA script failed to load
					BGC.track._abort = true;
					break;
				case "loading":
					BGC.log("waiting for GA script", str);
					return;
					break;
				default:
					BGC.log("loading GA script", str);
					BGC.loadscript(url, function () { BGC.track("IGNORE"); });
					return;
			}
		}
			
		var t, tracker;
		
		while (t = BGC.track._trackingstrings.shift()) {
			if (!BGC.track._abort) {
				BGC.log("trackPageview", t.str);
				for (var i = 0, l = BGC.track._trackers.length; i < l; i++) {
					if (typeof BGC.track._trackers[i]._trackPageview === "function") {
						tracker = BGC.track._trackers[i];
					} else {
						tracker = BGC.track._trackers[i] = _gat._getTracker(BGC.track._trackers[i]);
					}
					
					if (t.str) {
						tracker._trackPageview(t.str);
					} else {
						tracker._trackPageview();
					}
				}
			} else {
				BGC.log("tracking aborted", t.str);
			}
			
			if (typeof t.callback === "function") {
				t.callback();
			}
		}
	} catch (err) { // don't let issues with tracking break the rest of the module
		BGC.log(err, BGC.loadscript[url]);
		if (typeof callback === "function") {
			callback();
		}
	}
};

BGC.track.init = function () {
	for (var i = 0; i < arguments.length; i++) {
		BGC.track._trackers.push(arguments[i]);
	}
};

BGC.track._abort = false;

BGC.track._trackers = [];

BGC.track._trackingstrings = [];

// on-demand script loading

BGC.loadscript = function (url, callback) {
	if (!BGC.loadscript[url]) {
		BGC.loadscript[url] = "loading";
		var done = false, head = document.getElementsByTagName('head')[0], script = document.createElement('script');
	    script.setAttribute('type', 'text/javascript');
	    script.setAttribute('src', url);
	    script.onload = script.onreadystatechange = script.onerror = function () {
	    	BGC.log(url, "readystate", this.readyState);
            if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
                done = true;
                BGC.loadscript[url] = "complete";
                if (typeof callback === "function") {
					callback();
				}
            	script.onload = script.onreadystatechange = script.onerror = null; 
                head.removeChild(script);
            }
        };
        
	    head.appendChild(script);
	}
};

// cookie, querystring, and dom utilities

BGC.cookie = function (name, value, options) { // adapted from http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (!isNaN(options)) { // options can be an object, or a number representing days to expiration
        	options = {
        		expires: options * 1 // coerce to number in case we've received a string from Flash
        	};
        }
        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
        }
        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, l = cookies.length; i < l; i++) {
                var cookie = cookies[i].replace(/^\s+|\s+$/g, "");
                // 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;
    }
};

BGC.query = (function () {
	var qString, queryStart, query, parts, bits, subbits, returnVals = {};
	qString = window.location.toString();
	queryStart = qString.indexOf('?');
	if (queryStart === -1) {
		return returnVals;
	}
	query = qString.substring(queryStart + 1, qString.length);
	parts = query.split("&");
	for (var i = 0; i < parts.length; i++) {
		bits = parts[i].split("=");
		if (bits[1]) {
			subbits = bits[1].split("#");
			returnVals[bits[0].toLowerCase()] = subbits[0]; // query properties are lowercase!
		}
	}
	return returnVals;
}) ();

BGC.getPageSize = function () {
	var x = Math.max(document.documentElement.scrollWidth || document.body.scrollWidth, document.body.offsetWidth);
	var y = Math.max(document.documentElement.scrollHeight || document.body.scrollHeight, document.body.offsetHeight);
	return {"x": x, "y": y};
};

BGC.getViewportSize = function () {
	var x = self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
	var y = self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
	return {"x": x, "y": y};
};

BGC.getScrollOffset = function () {
	var x = self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
	var y = self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
	return {"x": x, "y": y};
};

BGC.getElemPosition = function (el) {
	var x = 0, y = 0;
	if (el.offsetParent) {
		do {
			x += el.offsetLeft;
			y += el.offsetTop;
		} while (el = el.offsetParent);
	}
	return {"x": x, "y": y};
};

BGC.popup = function(URL, windowName, width , height) {
	var w = screen.availWidth;
	var h = screen.availHeight;
	var leftPos = Math.round((w - width) / 2);
	var topPos = Math.round((h - height) / 2);
	var defaults = "scrollbars, resizable";
	var centerOnScreen = "top=" + topPos + ", left=" + leftPos + ", width=" + width + ", height=" + height;
	var options = centerOnScreen + " ," + defaults;
	var msgWindow = window.open(URL, windowName, options);
	if(!msgWindow) {
		return false;
	} else {
		msgWindow.creator = self;
		msgWindow.focus();
	}
  return true;
};

BGC.track.init("UA-5871316-7"); // TODO get correct profile code
BGC.track();
