// 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
};

// 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
 *
 * sample usage:
 *
 * INITIALIZE GA TRACKING, SPECIFY AS MANY UA ACCOUNT IDS AS NEEDED
 * BGC.track.init("UA-XXXXXXX-X", "UA-XXXXXXX-X", "UA-XXXXXXX-X");
 *
 * OPTIONAL GA CONFIGURATION SETTINGS, SEE http://code.google.com/apis/analytics/docs/gaJS/gaJSApiBasicConfiguration.html
 * and http://code.google.com/apis/analytics/docs/tracking/gaTrackingSite.html
 * BGC.track("_setSampleRate|50");
 * BGC.track("_setAllowHash|false");
 * BGC.track("_setAllowLinker|true");
 *
 * PAGEVIEW TRACKING
 * BGC.track();
 *
 * SYNTHETIC PAGEVIEW TRACKING WITH OPTIONAL CALLBACK
 * BGC.track("/some/pageview", function () { BGC.log("/some/pageview callback fired"); }); 
 *
 * EVENT TRACKING WITH OPTIONAL CALLBACK, SEE http://code.google.com/apis/analytics/docs/tracking/eventTrackerOverview.html
 * BGC.track("eventcat|eventaction|label|8", function () { BGC.log("eventcat|eventaction callback fired"); }); 
 */

BGC.track = function (str, callback) { // the public method for pageview and event tracking
	BGC.track._queue(str, callback);
	BGC.track._execute();
};

BGC.track._queue = function (str, callback) { // queues all tracking requests
	if (!BGC.track._abort) {
		BGC.track._trackingstrings.push({
			str: str,
			callback: callback
		});
		BGC.log("GA queue", BGC.track._trackingstrings);
	}
};

BGC.track._execute = function () { // executes all queued tracking requests
	if (BGC.track._ready) {
		var t, ev, tracker;
		while ((t = BGC.track._trackingstrings.shift())) {
			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) {
					// GA configuration methods (_setVar, _setSampleRate, _setSessionTimeout) ?
					// or cross-domain tracking methods (_setCookiePath, _cookiePathCopy, _setDomainName, _setAllowHash, _setAllowLinker, _link etc) ?
					if (t.str.match(/^_(set|cookie|link)[a-zA-Z]*\|/)) {
						ev = t.str.split("|");
						// should argument be of type boolean or number?
						if (ev[1].toLowerCase() === "true") {
							ev[1] = true;
						} else if (ev[1].toLowerCase() === "false") {
							ev[1] = false;
						} else if (!isNaN(ev[1])) {
							ev[1] = ev[1] * 1;
						}
						tracker[ev[0]](ev[1]);
						BGC.log("GA configuration", ev[0], ev[1]);
					// event API call ?
					} else if (t.str.indexOf("|") > -1 && typeof tracker._trackEvent === "function") {
						ev = t.str.split("|");
						if (ev.length === 4) {
							ev[3] = ev[3] * 1; // try to cast "value" argument to integer
						}
						tracker._trackEvent.apply(null, ev);
						BGC.log("GA trackEvent", ev);
					} else { // "named" pageview tracking call
						tracker._trackPageview(t.str);
						BGC.log("GA trackPageview", t.str);
					}
				} else { // default pageview tracking call
					tracker._trackPageview();
					BGC.log("GA trackPageview");
				}
			}
			
			if (typeof t.callback === "function") {
				t.callback();
			}
		}
		
	}
};

BGC.track.init = function () {
	var url = BGC.config.gaURL;
	//url += "?nocache=" + new Date(); // force it to load over the wire for testing
	//url = "badurl.js"; // for testing tracking script load error
		
	for (var i = 0; i < arguments.length; i++) {
		BGC.track._trackers.push(arguments[i]); // queue all the GA account IDs
	}
	
	if (typeof _gat === "undefined" && !BGC.loadscript[url]) { // need to load the GA script
		BGC.log("GA loading script");
		BGC.loadscript(url, function () { // our callback function will activate and call the BGC.track._execute() method after the GA script loads
			if (typeof _gat === "undefined" && BGC.loadscript[url] === "complete") {
				BGC.track._abort = true;
				BGC.log("GA tracking aborted");
			} else {
				// execute the previously queued tracking calls
				BGC.log("GA script loaded");
				BGC.track._ready = true;
				BGC.track._execute();
			}
		});
	}
};

BGC.track._abort = false;

BGC.track._ready = 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 || BGC.cookie.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 && (!isNaN(options.expires) || options.expires.toUTCString)) {
            var date;
            if (!isNaN(options.expires)) {
                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;
    }
};

// extending cookie object to make it possible to set cookie options from Flash externalInterface

BGC.cookie.options = {};

BGC.cookie.setOption = function (name, value) {
	BGC.cookie.options[name] = value;
};

BGC.cookie.clearOptions = function () {
	BGC.cookie.options = {};
};

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;
};