var ProtectedPage = {
    
    init : function () {
        if(ProtectedPage.weShouldProtectThisPage()) {
            ProtectedPage.redirectToTheSignInPage();
        }
    },
    
    weShouldProtectThisPage : function () {
        return isProtectedPage() && !isAuthenticated();
    },
    
    redirectToTheSignInPage : function () {
        window.location.replace("/signin?message=protected&loginSuccessRedirectUrl=" + window.location);
    }
};

ProtectedPage.init();
;
(function($){$.tiny=$.tiny||{};$.tiny.scrollbar={options:{axis:'y',wheel:40,scroll:true,size:'auto',sizethumb:'auto'}};$.fn.tinyscrollbar=function(options){var options=$.extend({},$.tiny.scrollbar.options,options);this.each(function(){$(this).data('tsb',new Scrollbar($(this),options));});return this;};$.fn.tinyscrollbar_update=function(sScroll){return $(this).data('tsb').update(sScroll);};function Scrollbar(root,options){var oSelf=this;var oWrapper=root;var oViewport={obj:$('.viewport',root)};var oContent={obj:$('.overview',root)};var oScrollbar={obj:$('.scrollbar',root)};var oTrack={obj:$('.track',oScrollbar.obj)};var oThumb={obj:$('.thumb',oScrollbar.obj)};var sAxis=options.axis=='x',sDirection=sAxis?'left':'top',sSize=sAxis?'Width':'Height';var iScroll,iPosition={start:0,now:0},iMouse={};function initialize(){oSelf.update();setEvents();return oSelf;}
this.update=function(sScroll){oViewport[options.axis]=oViewport.obj[0]['offset'+sSize];oContent[options.axis]=oContent.obj[0]['scroll'+sSize];oContent.ratio=oViewport[options.axis]/oContent[options.axis];oScrollbar.obj.toggleClass('disable',oContent.ratio>=1);oTrack[options.axis]=options.size=='auto'?oViewport[options.axis]:options.size;oThumb[options.axis]=Math.min(oTrack[options.axis],Math.max(0,(options.sizethumb=='auto'?(oTrack[options.axis]*oContent.ratio):options.sizethumb)));oScrollbar.ratio=options.sizethumb=='auto'?(oContent[options.axis]/oTrack[options.axis]):(oContent[options.axis]-oViewport[options.axis])/(oTrack[options.axis]-oThumb[options.axis]);iScroll=(sScroll=='relative'&&oContent.ratio<=1)?Math.min((oContent[options.axis]-oViewport[options.axis]),Math.max(0,iScroll)):0;iScroll=(sScroll=='bottom'&&oContent.ratio<=1)?(oContent[options.axis]-oViewport[options.axis]):isNaN(parseInt(sScroll))?iScroll:parseInt(sScroll);setSize();};function setSize(){oThumb.obj.css(sDirection,iScroll/oScrollbar.ratio);oContent.obj.css(sDirection,-iScroll);iMouse['start']=oThumb.obj.offset()[sDirection];var sCssSize=sSize.toLowerCase();oScrollbar.obj.css(sCssSize,oTrack[options.axis]);oTrack.obj.css(sCssSize,oTrack[options.axis]);oThumb.obj.css(sCssSize,oThumb[options.axis]);};function setEvents(){oThumb.obj.bind('mousedown',start);oThumb.obj[0].ontouchstart=function(oEvent){oEvent.preventDefault();oThumb.obj.unbind('mousedown');start(oEvent.touches[0]);return false;};oTrack.obj.bind('mouseup',drag);if(options.scroll&&this.addEventListener){oWrapper[0].addEventListener('DOMMouseScroll',wheel,false);oWrapper[0].addEventListener('mousewheel',wheel,false);}
else if(options.scroll){oWrapper[0].onmousewheel=wheel;}};function start(oEvent){iMouse.start=sAxis?oEvent.pageX:oEvent.pageY;var oThumbDir=parseInt(oThumb.obj.css(sDirection));iPosition.start=oThumbDir=='auto'?0:oThumbDir;$(document).bind('mousemove',drag);document.ontouchmove=function(oEvent){$(document).unbind('mousemove');drag(oEvent.touches[0]);};$(document).bind('mouseup',end);oThumb.obj.bind('mouseup',end);oThumb.obj[0].ontouchend=document.ontouchend=function(oEvent){$(document).unbind('mouseup');oThumb.obj.unbind('mouseup');end(oEvent.touches[0]);};return false;};function wheel(oEvent){if(!(oContent.ratio>=1)){oEvent=$.event.fix(oEvent||window.event);var iDelta=oEvent.wheelDelta?oEvent.wheelDelta/120:-oEvent.detail/3;iScroll-=iDelta*options.wheel;iScroll=Math.min((oContent[options.axis]-oViewport[options.axis]),Math.max(0,iScroll));oThumb.obj.css(sDirection,iScroll/oScrollbar.ratio);oContent.obj.css(sDirection,-iScroll);oEvent.preventDefault();};};function end(oEvent){$(document).unbind('mousemove',drag);$(document).unbind('mouseup',end);oThumb.obj.unbind('mouseup',end);document.ontouchmove=oThumb.obj[0].ontouchend=document.ontouchend=null;return false;};function drag(oEvent){if(!(oContent.ratio>=1)){iPosition.now=Math.min((oTrack[options.axis]-oThumb[options.axis]),Math.max(0,(iPosition.start+((sAxis?oEvent.pageX:oEvent.pageY)-iMouse.start))));iScroll=iPosition.now*oScrollbar.ratio;oContent.obj.css(sDirection,-iScroll);oThumb.obj.css(sDirection,iPosition.now);}
return false;};return initialize();};})(jQuery);;
/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

;
/*!
 * jQuery Tools v1.2.6 - The missing UI library for the Web
 * 
 * tooltip/tooltip.js
 * 
 * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
 * 
 * http://flowplayer.org/tools/
 * 
 */
(function(a){a.tools=a.tools||{version:"v1.2.6"},a.tools.tooltip={conf:{effect:"toggle",fadeOutSpeed:"fast",predelay:0,delay:30,opacity:1,tip:0,fadeIE:!1,position:["top","center"],offset:[0,0],relative:!1,cancelDefault:!0,events:{def:"mouseenter,mouseleave",input:"focus,blur",widget:"focus mouseenter,blur mouseleave",tooltip:"mouseenter,mouseleave"},layout:"<div/>",tipClass:"tooltip"},addEffect:function(a,c,d){b[a]=[c,d]}};var b={toggle:[function(a){var b=this.getConf(),c=this.getTip(),d=b.opacity;d<1&&c.css({opacity:d}),c.show(),a.call()},function(a){this.getTip().hide(),a.call()}],fade:[function(b){var c=this.getConf();!a.browser.msie||c.fadeIE?this.getTip().fadeTo(c.fadeInSpeed,c.opacity,b):(this.getTip().show(),b())},function(b){var c=this.getConf();!a.browser.msie||c.fadeIE?this.getTip().fadeOut(c.fadeOutSpeed,b):(this.getTip().hide(),b())}]};function c(b,c,d){var e=d.relative?b.position().top:b.offset().top,f=d.relative?b.position().left:b.offset().left,g=d.position[0];e-=c.outerHeight()-d.offset[0],f+=b.outerWidth()+d.offset[1],/iPad/i.test(navigator.userAgent)&&(e-=a(window).scrollTop());var h=c.outerHeight()+b.outerHeight();g=="center"&&(e+=h/2),g=="bottom"&&(e+=h),g=d.position[1];var i=c.outerWidth()+b.outerWidth();g=="center"&&(f-=i/2),g=="left"&&(f-=i);return{top:e,left:f}}function d(d,e){var f=this,g=d.add(f),h,i=0,j=0,k=d.attr("title"),l=d.attr("data-tooltip"),m=b[e.effect],n,o=d.is(":input"),p=o&&d.is(":checkbox, :radio, select, :button, :submit"),q=d.attr("type"),r=e.events[q]||e.events[o?p?"widget":"input":"def"];if(!m)throw"Nonexistent effect \""+e.effect+"\"";r=r.split(/,\s*/);if(r.length!=2)throw"Tooltip: bad events configuration for "+q;d.bind(r[0],function(a){clearTimeout(i),e.predelay?j=setTimeout(function(){f.show(a)},e.predelay):f.show(a)}).bind(r[1],function(a){clearTimeout(j),e.delay?i=setTimeout(function(){f.hide(a)},e.delay):f.hide(a)}),k&&e.cancelDefault&&(d.removeAttr("title"),d.data("title",k)),a.extend(f,{show:function(b){if(!h){l?h=a(l):e.tip?h=a(e.tip).eq(0):k?h=a(e.layout).addClass(e.tipClass).appendTo(document.body).hide().append(k):(h=d.next(),h.length||(h=d.parent().next()));if(!h.length)throw"Cannot find tooltip for "+d}if(f.isShown())return f;h.stop(!0,!0);var o=c(d,h,e);e.tip&&h.html(d.data("title")),b=a.Event(),b.type="onBeforeShow",g.trigger(b,[o]);if(b.isDefaultPrevented())return f;o=c(d,h,e),h.css({position:"absolute",top:o.top,left:o.left}),n=!0,m[0].call(f,function(){b.type="onShow",n="full",g.trigger(b)});var p=e.events.tooltip.split(/,\s*/);h.data("__set")||(h.unbind(p[0]).bind(p[0],function(){clearTimeout(i),clearTimeout(j)}),p[1]&&!d.is("input:not(:checkbox, :radio), textarea")&&h.unbind(p[1]).bind(p[1],function(a){a.relatedTarget!=d[0]&&d.trigger(r[1].split(" ")[0])}),e.tip||h.data("__set",!0));return f},hide:function(c){if(!h||!f.isShown())return f;c=a.Event(),c.type="onBeforeHide",g.trigger(c);if(!c.isDefaultPrevented()){n=!1,b[e.effect][1].call(f,function(){c.type="onHide",g.trigger(c)});return f}},isShown:function(a){return a?n=="full":n},getConf:function(){return e},getTip:function(){return h},getTrigger:function(){return d}}),a.each("onHide,onBeforeShow,onShow,onBeforeHide".split(","),function(b,c){a.isFunction(e[c])&&a(f).bind(c,e[c]),f[c]=function(b){b&&a(f).bind(c,b);return f}})}a.fn.tooltip=function(b){var c=this.data("tooltip");if(c)return c;b=a.extend(!0,{},a.tools.tooltip.conf,b),typeof b.position=="string"&&(b.position=b.position.split(/,?\s/)),this.each(function(){c=new d(a(this),b),a(this).data("tooltip",c)});return b.api?c:this}})(jQuery);
;
/**
 * 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 secs = options.expires, t = options.expires = new Date();
            //t.setDate(t.getDate() + days);
            t.setTime( t.getTime() + secs );
        }

        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;
};
;
function showPromoBox(divId, imageUrl) {
    (jQuery)(divId).show();  
    setImageSourceById(divId, imageUrl);
}

function showPromoBoxIfVisitorIsJoined(divId, imageUrl) {
    isJoinedOrAuthenticated = (isJoined() || isAuthenticated()); 
    (jQuery)(divId).toggle(isJoinedOrAuthenticated);
    if ( isJoinedOrAuthenticated ) {
     setImageSourceById(divId, imageUrl);  
   }
}

function showPromoBoxIfVisitorIsUnjoined(divId, imageUrl) {
    (jQuery)(divId).toggle(isUnjoined());
    if ( isUnjoined() ) {
     setImageSourceById(divId, imageUrl);  
   }
}

function setImageSourceById(divId, imageUrl) {
   if ( imageUrl != '') {
      (jQuery)(divId + " img").attr('src', imageUrl);  
   }
}
;
var Login = {
  
    SESSION_EXPIRED_URL : '/session-expired',
    defaultAccountValue : null,

    init : function() {
        Login.setUpHeader();
        Login.setUpLoginPage();
        Login.hideLoginFormInHeader();
    },
    
    hideLoginFormInHeader: function() {
        if (jQuery("#onPageLoginForm").length > 0) {
            jQuery('#returnVisitor form').hide();
        }
    },
  
    setUpHeader : function () {
        Login.setUpSubNavigationForTheHeaderLoginForm();
        Login.setUpTheHeaderLoginForm();
    },
    
    setUpSubNavigationForTheHeaderLoginForm : function() {
        jQuery(".subNavigation").click(function() {
            Login.updateUserAreaSubNavigation(this);
        });
    },
    
    updateUserAreaSubNavigation : function(clickedItem) {
        var subNavWrapper = jQuery("#subNavWrapper"),
            panelIsNotShown = subNavWrapper.is(":hidden"),
            arrowElement = subNavWrapper.find("#arrow");

        // Slide down the panel if it is not shown
        if(panelIsNotShown) {
            subNavWrapper.slideDown();
            jQuery(".signedIn").addClass('expanded');
        } else {
            arrowElement.removeClass();
        }

        Login.showCorrectSubNavigationItem(clickedItem);
    },
    
    showCorrectSubNavigationItem : function(clickedItem) {
        var subNavWrapper = jQuery("#subNavWrapper"),
            thisSubNav = subNavWrapper.find("." + clickedItem.id),
            arrowElement = subNavWrapper.find("#arrow"),
            subNavList = subNavWrapper.find("ul");
            
        arrowElement.addClass(clickedItem.id);

        jQuery("ul.navigation").find('a.selected').removeClass('selected');
        jQuery(clickedItem).addClass('selected');

        subNavList.fadeOut('slow');
        thisSubNav.fadeIn('slow');
    },
    
    setUpTheHeaderLoginForm : function() {
        Login.setUpTheHeaderLoginFormPasswordField();
        Login.setUpTheHeaderLoginFormAccountIDField();
        Login.setUpTheHeaderLoginFormSubmitButton();
        Login.setUpTheHeaderLoginFormSubmit();
        
        if(Login.theFormWillRedirectToTheSessionExpiredUrl()) {
            Login.forceLoginRedirectToHomepage();
        }
    },
    
    theFormWillRedirectToTheSessionExpiredUrl : function () {
        var redirectUrl = jQuery('#onSuccessRedirectURL').val();
        var sessionExpiredUrl = 'https://' + window.location.hostname + Login.SESSION_EXPIRED_URL;
        
        return redirectUrl == sessionExpiredUrl;
    },
    
    forceLoginRedirectToHomepage : function() {
        jQuery('[id=onSuccessRedirectURL]').val('https://' + window.location.hostname);
    },
    
    setUpTheHeaderLoginFormPasswordField : function() {
        jQuery("#passwordClear").focus(function() {
            jQuery(this).hide();
            jQuery("#password").show().focus();
        }).show();

        jQuery("#password").focus(function() {
            if (Login.isPasswordEmpty()) {              
              jQuery("#passwordTooltip").show();
            }
            jQuery('#signinButtonTooltip').hide();
        }).keyup(function() {
            if (!Login.isPasswordEmpty()) {             
              jQuery("#passwordTooltip").hide();
            } else {
              jQuery("#passwordTooltip").show();                
            }
        }).blur(function() {
            if(Login.isPasswordEmpty()) {
                jQuery(this).hide();
                jQuery("#passwordClear").show();
            }
            jQuery("#passwordTooltip").hide();
        }).hide();
    },
    
    setUpTheHeaderLoginFormAccountIDField : function() {

        jQuery("#username").focus(function() {
            if(Login.isUsernameEmpty()) {
                jQuery(this).val('');
                jQuery("#usernameTooltip").show();
            }
            jQuery('#signinButtonTooltip').hide();
        }).keyup(function() {
            if (jQuery(this).val() != '') {
                Login.hideUsernameTooltips();
            } else {
                jQuery("#usernameTooltip").show();
            }
        }).blur(function() {
            if(jQuery(this).val() == '') {
                jQuery(this).val(Login.getDefaultAccountValue());
            }
            Login.hideUsernameTooltips();
        });
    },
    
    hideUsernameTooltips : function() {
        jQuery("#usernameTooltip").hide();
        jQuery('#signinButtonTooltip').hide();
    },
    
    setUpTheHeaderLoginFormSubmitButton : function() {
        jQuery("#loginFormSubmit").click(function() {
            jQuery(this).closest("form").submit();
        });
    },
    
    setUpTheHeaderLoginFormSubmit : function() {
        jQuery('[name="returningVisitor"]').submit(function() {
            if (Login.areBothUsernameAndPasswordEmpty()) {
                jQuery('#username').focus();
                jQuery('#signinButtonTooltip').show();
            } else if (Login.isPasswordEmpty()) {
                jQuery('#passwordClear').focus();
            } else if (Login.isUsernameEmpty()) {
                jQuery('#username').focus();
            } else {
                return true;
            }
            return false;
        });
    },
    
    isUsernameEmpty : function() {
        return jQuery('#username').val()==Login.getDefaultAccountValue()
            || jQuery('#username').val()=='';
    },
    
    isPasswordEmpty : function() {
        return jQuery('#password').val()=='';
    },
    
    areBothUsernameAndPasswordEmpty : function() {
        return Login.isUsernameEmpty() && Login.isPasswordEmpty();
    },
    
    setUpLoginPage : function() {
        Login.setUpTheOnPageLoginForm();
    },
    
    setUpTheOnPageLoginForm : function() {
        Login.setUpTheOnPageLoginFormAccountIDField();
        Login.setUpTheOnPageLoginFormPasswordField();
        Login.setUpTheOnPageLoginFormSubmit();
        
        if(Login.thereWasAnErrorLoggingIn()) {
            Login.showTheErrorMessage();
            Login.markTheLoginFormInputsAsInvalid();
        }
    },
    
    setUpTheOnPageLoginFormAccountIDField : function() {
        var defaultAccountIDValue = jQuery('form#onPageLoginForm #loginPageUsername').val();

        jQuery('form#onPageLoginForm #loginPageUsername').focus(function() {
            if(jQuery(this).val() == defaultAccountIDValue) {
                jQuery(this).val('');
            }
        });

        jQuery('form#onPageLoginForm #loginPageUsername').blur(function() {
            if(jQuery(this).val() == '') {
                jQuery(this).val(defaultAccountIDValue);
            }
        });
    },
    
    setUpTheOnPageLoginFormPasswordField : function() {
        jQuery("form#onPageLoginForm #loginPagePasswordClear").focus(function() {
            jQuery(this).hide();
            jQuery("form#onPageLoginForm #loginPagePassword").show().focus();
        }).show();

        jQuery("form#onPageLoginForm #loginPagePassword").blur(function() {
            if(jQuery(this).val() == '') {
                jQuery(this).hide();
                jQuery("form#onPageLoginForm #loginPagePasswordClear").show();
            }
        }).hide();
    },
    
    setUpTheOnPageLoginFormSubmit : function() {
        jQuery('#onPageLoginForm').submit(function() {
            return Login.loginFormIsOkayToSubmit(jQuery('form#onPageLoginForm #loginPageUsername'), jQuery("form#onPageLoginForm #loginPagePassword"));
        });
    },
    
    thereWasAnErrorLoggingIn : function() {
        var message = Login.getUrlParameter("message");
        return (message == "error" || message == "duplicated" || message == "forgotten" || message == "blocked" || message == "protected");
    },
    
    showTheErrorMessage : function() {
        var className = Login.getUrlParameter("message") + 'Message';
        jQuery("." + className).show();
    },
    
    getUrlParameter : function(urlParameterToReturn) {
        // use a RegExp to retrieve the selected parameter from the url query string
        var output = RegExp("[\\?&]" + urlParameterToReturn + "=([^&#]*)").exec(location.search);
        if(( output instanceof Array) && (output.length > 0)) {
            return output[1];
        } else {
            return null;
        }
    },
    
    markTheLoginFormInputsAsInvalid : function() {
        jQuery(".signInFormWrapper input[type=text], .signInFormWrapper input[type=password]").addClass("errorMessageInput");
    },
    
    redirectToSessionExpiredURL : function () {
        window.location.replace(Login.getSessionExpiredURL());
    },

    getSessionExpiredURL : function () {
        return 'http://www.bovada.lv' + Login.SESSION_EXPIRED_URL;
    },
    
    getDefaultAccountValue : function() {
        if (Login.defaultAccountValue==null) {
            Login.defaultAccountValue = jQuery('#username').val();
        }
        return Login.defaultAccountValue;
    }
};
;
jQuery(document).ready(function($) {

    var UPDATE_BALANCE_TIMEOUT_MILLIS = 60000;
    var messageTabHtml = '';
    var updateBalanceTimerId;

    initiate();

    function initiate() {
        TimeZone.init();
        Forms.init();
        Login.init();
        
        messageTabHtml = $('#tabs .messages').html();
        
        UserProfile.getUserProfile();
        createEventListenerForUserProfile();
        createOnBalanceChangedEventListener();
        createUpdateAccountSummaryTimer();
        
        setUpTheDynamicNavigation();
        checkIfUserIsSignedInAndDisplayCorrectHeaderDiv();
        headerWelcomeMessageFirstVisitor();
        addStylesForNewVisitor();
        
        addFirstAndLastClassToTeasers();
        addFirstAndLastClassToHNav();
        setupOddAndEvenTableRows();
        
        openPopup();
        
    }
    
    function createEventListenerForUserProfile() {
        WebPlatformAccountServicesEvents.bindToUserProfileReadyEvent(displaySignedInUsersDetails);
    }
    
    function displaySignedInUsersDetails() {
        $('#accountNumberHolder').html(UserProfile.getUserId());
        $('#accountNumberHolderForHeaderMessage').html(UserProfile.getUserId());
        $('#accountUserNameHolderForHeader').html(UserProfile.getUserName());
        $('#messageCountHolder').html(UserProfile.getMessageCount());
        $('#accountCurrencySymbolHolder').html(UserProfile.getCurrencySymbol());
        $('#tabs .messages').html(messageTabHtml + " (" + UserProfile.getMessageCount() + ")");
        $('#accountBalanceHolder').html(UserProfile.getFormattedBalance());
    }
    
    function createOnBalanceChangedEventListener() {
        WebPlatformAccountServicesEvents.bindToBalanceChangedEvent(onBalanceChangedCallback);
    }

    function onBalanceChangedCallback(event, newBalance) {
        displayAccountBalance(newBalance);
        createUpdateAccountSummaryTimer();
    }

    function displayAccountBalance(balance) {
        $('#accountBalanceHolder').html(balance);
    }

    function createUpdateAccountSummaryTimer() {
        updateBalanceTimerId = WebPlatformEvents.recreateTimer(updateBalanceTimerId, UPDATE_BALANCE_TIMEOUT_MILLIS, function() { UserProfile.getAccountBalance(); });
    }
    
    function setUpTheDynamicNavigation() {
        showDefaultDynamicNavigationCategory();
        makeDynamicMenuItemsExpandWhenClicked();
    }

    function showDefaultDynamicNavigationCategory() {
        $(".vNavigation ul li ul").hide();
        $(".vNavigation ul li a.active").siblings().show();
    }

    function makeDynamicMenuItemsExpandWhenClicked() {
        $(".vNavigation > ul > li > a").attr("href", "javascript:void(0);").click(function() {
            $(this).next("ul").slideToggle(400);
        });
    }
    
    function checkIfUserIsSignedInAndDisplayCorrectHeaderDiv() {
        //Show the form or the logged in div
        $('#signedIn').toggle(isAuthenticated());
        $('#signedInTop').toggle(isAuthenticated());                                
        $('#returnVisitor').toggle(!isAuthenticated());
        $('#welcomeMessage').toggle(checkDisplayWelcomeMsg());
    }

    function checkDisplayWelcomeMsg() {
      return (isUnjoined() && !$.cookie("w_msg"));
    }

    // welcome message first visitor
    function headerWelcomeMessageFirstVisitor() {
        $("#open").click(function() {
            $("div#welcomeMessageContentWrap").slideDown("slow");
            $("#welcomeMessageTab #toggle").addClass('down');
            $("#welcomeMessageTab #toggle").removeClass('up');
        });
        
        $("#close").click(function(){
            $("div#welcomeMessageContentWrap").slideUp("slow");
            $("#welcomeMessageTab #toggle").addClass('up');
            $("#welcomeMessageTab #toggle").removeClass('down');
        });
        
        $("#toggle a").click(function () {
            $("#toggle a").toggle();
        });
        
        $(".closeMessage").click(function () {
            $("#welcomeMessage").fadeToggle("slow", "linear");
            $.cookie("w_msg", 1, { domain: '.bovada.lv' });
        });
    }
    
    function addStylesForNewVisitor() {
        if(isUnjoined()) {
            $("#returnVisitor").addClass("newVisitor");
            
            if(isJoinPage()) {
                $('#forgotYourDetailsReturn').addClass("unjoinedLink");
            }
        }
    }
  
    function isJoinPage() {
        return window.location.pathname == '/join';
    }
    
    function addFirstAndLastClassToTeasers() {
        // add first and last class to the teasers
        $(".promoArea .promoItem:last-child").addClass("promoItemLastChild");
        $(".promoArea .promoItem:first-child").addClass("promoItemFirstChild");
        $(".promoArea .promoItem:last-child.promoItem:first-child").addClass("promoItemOnlyChild");
    }

    function addFirstAndLastClassToHNav() {
        // add first and last class to the fourth navigation
        $(".hNavigation ul li:first-child a").addClass("hNavFirstChild");
    }
    
    function setupOddAndEvenTableRows() {
        $("table.wysiwyg tr:odd,table.tableNoBorders tr:odd").addClass("odd");
        $("table.wysiwyg tr:even,table.tableNoBorders tr:even").addClass("even");
        $("table.wysiwyg tr:first,table.tableNoBorders tr:first").addClass("first");
    }
    
  function openPopup() {  
      $("a.sitepopup").click(function () { 
        
          var height = "800";
          var width = "650";  
          var popupSettings = "scrollTo,resizable=1,scrollbars=1,location=0";
          var linkClasses = $(this).attr("class").split(" ");
          var hasClassWithSize = false;
          
          $.each(linkClasses, function(index,value){
            if (value.match(/\bsize/)) {
              hasClassWithSize = true;
              popupSize = value.substring(4).split("x");
              return popupSize; 
            }
          });
          if (hasClassWithSize) {
            var width = popupSize[0];
            var height = popupSize[1];
          }
          
          popupSettings = "height=" + height + ",width=" + width + "," + popupSettings;
          
          newWindow = window.open(this.href, 'MyPopup', popupSettings);  
          return false;  
    });
  }
  
});


function openCasinoGame(gameId) {
    if(isAuthenticated()) {
        //TODO: Open Game FOR REAL
    } else {
        //TODO: Open Game FOR FUN
    }
};
/* accounting.js v0.3-alpha - http://josscrowcroft.github.com/accounting.js */
(function(p,z){function q(a){return!!(a===""||a&&a.charCodeAt&&a.substr)}function m(a){return u?u(a):v.call(a)==="[object Array]"}function r(a){return v.call(a)==="[object Object]"}function s(a,b){for(var d in b)b.hasOwnProperty(d)&&a[d]==null&&(a[d]=b[d]);return a}function j(a,b,d){var c=[],e,h;if(!a)return c;if(w&&a.map===w)return a.map(b,d);for(e=0,h=a.length;e<h;e++)c[e]=b.call(d,a[e],e,a);return c}function n(a,b){a=Math.round(Math.abs(a));return isNaN(a)?b:a}function x(a){var b=c.settings.currency.format;typeof a==="function"&&(a=a());if(q(a)&&a.match("%v"))return{pos:a,neg:a.replace("-","").replace("%v","-%v"),zero:a};else if(!a||!a.pos||!a.pos.match("%v"))return!q(b)?b:c.settings.currency.format={pos:b,neg:b.replace("%v","-%v"),zero:b};return a}var c={version:"0.3-alpha",settings:{currency:{symbol:"$",format:"%s%v",decimal:".",thousand:",",precision:2,grouping:3},number:{precision:0,grouping:3,thousand:",",decimal:"."}}},w=Array.prototype.map,u=Array.isArray,v=Object.prototype.toString,o=c.unformat=function(a,b){if(m(a))return j(a,function(a){return o(a,b)});var b=b||".",c=parseFloat((""+(a||0)).replace(RegExp("[^0-9-"+b+"]",["g"]),"").replace(b,"."));return!isNaN(c)?c:0},y=c.toFixed=function(a,b){var b=n(b,c.settings.number.precision),d=Math.pow(10,b);return(Math.round(a*d)/d).toFixed(b)},t=c.formatNumber=function(a,b,d,i){if(m(a))return j(a,function(a){return t(a,b,d,i)});var a=o(a),e=s(r(b)?b:{precision:b,thousand:d,decimal:i},c.settings.number),h=n(e.precision),f=a<0?"-":"",g=parseInt(y(Math.abs(a||0),h),10)+"",l=g.length>3?g.length%3:0;return f+(l?g.substr(0,l)+e.thousand:"")+g.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+e.thousand)+(h?e.decimal+y(Math.abs(a),h).split(".")[1]:"")},A=c.formatMoney=function(a,b,d,i,e,h){if(m(a))return j(a,function(a){return A(a,b,d,i,e,h)});var a=o(a),f=s(r(b)?b:{symbol:b,precision:d,thousand:i,decimal:e,format:h},c.settings.currency),g=x(f.format);return(a>0?g.pos:a<0?g.neg:g.zero).replace("%s",f.symbol).replace("%v",t(Math.abs(a),n(f.precision),f.thousand,f.decimal))};c.formatColumn=function(a,b,d,i,e,h){if(!a)return[];var f=s(r(b)?b:{symbol:b,precision:d,thousand:i,decimal:e,format:h},c.settings.currency),g=x(f.format),l=g.pos.indexOf("%s")<g.pos.indexOf("%v")?true:false,k=0,a=j(a,function(a){if(m(a))return c.formatColumn(a,f);else{a=o(a);a=(a>0?g.pos:a<0?g.neg:g.zero).replace("%s",f.symbol).replace("%v",t(Math.abs(a),n(f.precision),f.thousand,f.decimal));if(a.length>k)k=a.length;return a}});return j(a,function(a){return q(a)&&a.length<k?l?a.replace(f.symbol,f.symbol+Array(k-a.length+1).join(" ")):Array(k-a.length+1).join(" ")+a:a})};typeof module!=="undefined"&&module.exports?(module.exports=c,c.accounting=c):typeof define==="function"&&define.amd?define([],function(){return c}):(c.noConflict=function(a){return function(){p.accounting=a;c.noConflict=z;return c}}(p.accounting),p.accounting=c)})(this);
;
/**
* jHash v1.0.0
* http://jhash.codeplex.com
* 
* Copyright (c) 2010 Chris Pietschmann
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy of 
* this software and associated documentation files (the "Software"), to deal in the 
* Software without restriction, including without limitation the rights to use, copy, 
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the 
* following conditions:
* 
* The above copyright notice and this permission notice shall be included in all copies 
* or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function (window) {
    var hashChangeSupported = ('onhashchange' in window);
    var jHash = window.jHash = {
        jhash: "1.0.0",
        change: function (handler) {
            if (hashChangeSupported) {
                attachEvent(window, "hashchange", handler);
            } else {
                eventHandlers.push(handler);
            }
        },
        unbind: function (handler) {
            var i = 0, len = 0;
            if (hashChangeSupported) {
                detachEvent(window, "hashchange", handler);
            } else {
                arrayRemove(eventHandlers, eventHandlers.indexOf(handler));
            }
            return this;
        },
        val: function (name, value) {
            var ho = hashToObject(window.location.hash);
            if (arguments.length === 2) {
                ho[name.toLowerCase()] = (value === null ? '' : value);
                return this.set(this.root(), ho);
            } else if (arguments.length === 1 && typeof (name) === 'string') {
                return ho[name.toLowerCase()];
            }
            return ho;
        },
        root: function (value) {
            if (value === undefined) {
                return parseHashRoot(window.location.hash);
            }
            return this.set(value, this.val());
        },
        set: function (root, query) {
            if (arguments.length === 2) {
                window.location.hash = root + '?' + (typeof (query) === "string" ? query : objectToHash(query));
            } else {
                window.location.hash = root;
            }
            return this;
        },
        remove: function (name) {
            var ho = hashToObject(window.location.hash);
            ho[name.toLowerCase()] = undefined;
            return this.set(this.root(), ho);
        }
    };

    if (!hashChangeSupported) {
        window.setInterval(function () {
            var currentHash = window.location.hash;
            if (previousHashValue !== currentHash) {
                for (var i in eventHandlers) {
                    if( eventHandlers.hasOwnProperty( i ) ) {
                        eventHandlers[i].call(window);
                    }
                }
            }
            previousHashValue = currentHash;
        }, 200);
    }

    var eventHandlers = [],
        previousHashValue = window.location.hash,
        attachEvent = function (element, evtName, handler) {
            if (element.addEventListener) {
                element.addEventListener(evtName, handler, false);
            } else if (element.attachEvent) {
                element.attachEvent("on" + evtName, handler);
            } else {
                element["on" + evtName] += handler;
            }
        },
        detachEvent = function (element, evtName, handler) {
            if (element.removeEventListener) {
                element.removeEventListener(evtName, handler, false);
            } else if (element.detachEvent) {
                element.detachEvent("on" + evtName, handler);
            } else {
                element["on" + evtName] -= handler;
            }
        },
        arrayRemove = function (array, from, to) {
            /* function source: http://ejohn.org/blog/javascript-array-remove/ */
            var rest = array.slice((to || from) + 1 || array.length);
            array.length = from < 0 ? array.length + from : from;
            return array.push.apply(array, rest);
        },
        hashToObject = function (hash) {
            /* create a "dictionary" object for the passed in hash value */
            var obj = {}, pair = null, strHash = hash.substring(0, hash.length);
            if (strHash.indexOf("#") === 0) {
                strHash = strHash.substring(1, strHash.length);
            }
            var queryIndex = strHash.indexOf("?");
            if (queryIndex > -1) {
                strHash = strHash.substring(queryIndex + 1, strHash.length);
            }
            var parts = strHash.split("&");
            for (var i in parts) {
                if( parts.hasOwnProperty( i ) ) {
                    pair = parts[i].split("=");
                    obj[pair[0].toString().toLowerCase()] = pair[1];
                }
            }
            return obj;
        },
        objectToHash = function (object) {
            var s = "";
            for (var i in object) {
                if (object[i] !== undefined) {
                    if (s.length > 0) {
                        s += "&";
                    }
                    s += i.toString() + "=" + object[i].toString();
                }
            }
            return s;
        },
        parseHashRoot = function (hash) {
            var strHash = hash.substring(0, hash.length);
            if (strHash.indexOf("#") > -1) {
                strHash = strHash.substring(1, strHash.length);
            }
            if (strHash.indexOf("?") > -1) {
                strHash = strHash.substring(0, strHash.indexOf("?"));
            }
            return strHash;
        };
}(window));;
SinglePopupManager = (function($) {
	var _handle,
		_config = {},
		_lastRequestedConfig;
	
	return {
		open: function( config ) {
			var message='';
			
			_config = $.extend( { attrs:'status=no,toolbar=no,width=747,height=700,location=no,directories=no'}, _config );
			//_config = $.extend( { attrs:'status=no,toolbar=no,width=747,height=700,location=no,directories=no'}, config );
			_config = $.extend( _config, config );
			if( !_config.url ) {
				//cannot open popup without a URL. signal failure returning 'false'
				return false;
			}

			//_lastRequestedConfig = config;
			_handle = window.open( _config.url, _config.name, _config.attrs );
			if (!_handle) {
				message = 'A pop-up blocker prevented the opening of a window.\n\n' +
					'Please reduce the setting on your pop-up blocker or add slots.com to the list of "allowed sites" in your pop-up blockers settings.\n\n' +
					'Please contact our Customer Service team if you have further questions.';
				alert( message );
				return false;
			}
			_handle.focus();
			return true;
		},
	
		close: function() {
			if( _handle ) {
				_handle.close();
				_handle = null;
			}
		},
		
		isOpen: function() {
			return _handle && !_handle.closed;
		}		
	};
}(jQuery));

jQuery(document).ready( function($){ 
	var popupHandle;
	
	function openLobbyPopup(url) {
		var dimensions;

		//Popup with this class will take, by default, 90% of the screen estate, maintaining an aspect ratio of 1.33
		//dimensions = brandx.utils.Screen.zoomAt( 90, {aspect:1.33} );
		dimensions = { computedWidth: 814, computedHeight: 766 };

		//determine position of the popup
		var pos = brandx.utils.Screen.center( {width: dimensions.computedWidth, height: dimensions.computedHeight } );

		//console.log( "opening popup at " + pos.left + "," +  pos.top );
		SinglePopupManager.open( { 
				url:url, 
				name: 'singlepopup',
				attrs:'status=no,toolbar=no,width=' + dimensions.computedWidth +
					',height=' + dimensions.computedHeight +
					',top=' + pos.top +
					',left=' + pos.left +
					',location=no,resizable=no,directories=no' } );

	}
	
	$('a.popup').click( function(evt) { 
		var url = $(this).attr('href'),
			dimensions;
			
		evt.preventDefault();
		openLobbyPopup( url );
		return false;
	} );
} );


;
/**
* Common Utilities used across the Application
*
* @author D.Molin
*/

/**
 * To define a namespace function and, at the same time, 
 * put that same function into a "scope"  (global scope, in this case);)
 */
(function(name){
	function namespace(nspace) {
		var nspaces = !nspace ? '' : nspace.split('.'),
			parent = window,
			i = 0;
		for( i in nspaces ) {
			if( nspaces.hasOwnProperty(i) ) {
				if( typeof parent[nspaces[i]] === 'undefined' ) {
					parent[nspaces[i]] = {};
				}
				parent = parent[nspaces[i]];
			}
		}
		//let's return the innermost namespace, to allow for
		//immediate use..
		return parent;
	}
	namespace(name).namespace = namespace;
}());

(function($){
	/**
	* return the location hash value and normalize the value
	* across different browser implementations
	*/
	$.fn.locationHash = function() {
		var loc = $(this).attr('href');
		
		if( typeof loc === 'undefined' || loc.length === 0 ) {
			return '';
		}
		
		//strip full address, if present
		loc = loc.match(/#.*/);
		return (loc ? loc[0] : '');
	};
	
	
	/*-------------------------------------------
	* brandx.utils
	*---------------------------------------------*/
	namespace( 'brandx.utils');
	
	brandx.utils.openDomainURLInMainWindow = (function() {
		return function( url, isRelative ) {
			var message,
				mainWindow = null;

			if( !url ) {
				url = "/";
			}
			
			url = ( isRelative ? url : url.match(/^http/) ? url : location.protocol + '//' + location.host + url );
			if( window.opener && !window.opener.closed ) {
				try {
					window.opener.name = "mainwindow";
				} catch( error ) {}
			}
			mainWindow = window.open( url, "mainwindow" );
			if (!mainWindow) {
				message = 'A pop-up blocker prevented the opening of a window.\n\n' +
					'Please reduce the setting on your pop-up blocker or add slots.com to the list of "allowed sites" in your pop-up blockers settings.\n\n' +
					'Please contact our Customer Service team if you have further questions.';
				alert( message );
				return false;
			}
			
			if( mainWindow && !mainWindow.closed ) {
				mainWindow.focus();
			}
		};
	}());
	
	/*-------------------------------------------
	* brandx.utils.Math
	*---------------------------------------------*/
	brandx.utils.Math = {};
	(function(n){
		n.isNumeric = function( amount ) {
			return !n.isNotNumeric( amount );
		};
		
		n.isNotNumeric = function( amount ) {
			return isNaN(parseFloat(amount)) || !isFinite(amount);
		};
	}( brandx.utils.Math ));
	
	
	/*-------------------------------------------
	* brandx.utils.Money
	*---------------------------------------------*/
	brandx.utils.Money = {};
	(function(n){
		n.formatMoney = function( value ) {
			if( accounting ) {
				return accounting.formatMoney( value, { precision:2, thousands:',' } );
			} else {
				//no formatting at the moment
				return n.fromWhole( value );
			}
		};
		
		/**
		* convert a "whole" value to a currency value, using the last 2 digits as the decimal part
		*/
		n.fromWhole = function( amount ) {
			if(amount && brandx.utils.Math.isNumeric( amount ) ) {
				return parseFloat(amount / 100).toFixed(2);
			}
			else
				return ' -- ';
		};
		
		n.fromWholeWithCurrency = function( amount ) {
			return 'US$ ' + n.fromWhole( amount );
		};
		
	}( brandx.utils.Money ));

	
}(jQuery));

;
/**
* Utility function used for Publishing/Subscribing for events
*
* Note: the pub/sub logic, though simple, is HEAVILY based on Peter Higgins (dante@dojotoolkit.org) implementation, 
*       Loosely based on Dojo publish/subscribe API, limited in scope. 
*       Original is (c) Dojo Foundation 2004-2009. Released under either AFL or new BSD, see:
*       http://dojofoundation.org/license for more information.
*
* @author D.Molin
*/
(function($){
	
	namespace( 'brandx.events' );

	/*----------------------------------------
	* Internal privileged functions
	*-----------------------------------------*/
	
	// the topic/subscription hash
	var cache = {};

	function _publish(/* String */topic, /* Array? */args){
		// summary: 
		//    Publish some data on a named topic.
		// topic: String
		//    The channel to publish on
		// args: Array?
		//    The data to publish. Each array item is converted into an ordered
		//    arguments on the subscribed functions. 
		//
		// example:
		//    Publish stuff on '/some/topic'. Anything subscribed will be called
		//    with a function signature like: function(a,b,c){ ... }
		//
		//  |   $.publish("/some/topic", ["a","b","c"]);
		// dmolin: TODO: we have to allow for passing specific scope for bound events
		
		if( !cache[topic]) {
			return;
		}
		
		$.each(cache[topic], function(){
			try { this.apply( $, args || []); } catch( error ){}
		});
	}

	function _subscribe(/* String */topic, /* Function */callback){
		// summary:
		//    Register a callback on a named topic.
		// topic: String
		//    The channel to subscribe to
		// callback: Function
		//    The handler event. Anytime something is $.publish'ed on a 
		//    subscribed channel, the callback will be called with the
		//    published array as ordered arguments.
		//
		// returns: Array
		//    A handle which can be used to unsubscribe this particular subscription.
		//  
		// example:
		//  | $.subscribe("/some/topic", function(a, b, c){ /* handle data */ });
		//
		if(!cache[topic]){
			cache[topic] = [];
		}
		
		if( typeof callback !== 'function' ) {
			return;
		}
		
		cache[topic].push(callback);
		return [topic, callback]; // Array
	}

	function _unsubscribe(/* Array */handle){
		// summary:
		//    Disconnect a subscribed function for a topic.
		// handle: Array
		//    The return value from a $.subscribe call.
		// example:
		//  | var handle = $.subscribe("/something", function(){});
		//  | $.unsubscribe(handle);
		
		var t;
		
		if( typeof handle === 'undefined' || !$.isArray(handle) ) {
			return;
		}
		
		t = handle[0];
		if( cache[t] ) {
			$.each(cache[t], function(idx){
				if(this == handle[1]) {
					cache[t].splice(idx, 1);
				}
			});
		} 
	}
	
	/*----------------------------------------
	* Exposed API interface
	*-----------------------------------------*/
	
	/**
	* Verify that the required scoped event namespace object exists.
	* If not, it is created with the corresponding publishing/subscribing functions
	* Example: if you want to have brandx.events.game.GameInfo with publish, subscribe, unsubscribe,
	* you just need to call (before actually using it):
	*
	*   brandx.events.require( "game.GameInfo" );
	*
	* After that, you will be able to access:
	*
	*	brandx.events.game.GameInfo.publish()/subscribe()/unsubscribe()
	*
	* that's all!
	*/
	brandx.events.require = function( namespacedEvent ) {
		var completeNamespace = "brandx.events",
			nspace;
			
		if( !namespacedEvent || namespacedEvent.length === 0 ) {
			return; //no-op
		}
		
		completeNamespace += (namespacedEvent.charAt(0) === '.' ? namespacedEvent : "." + namespacedEvent );
		
		nspace = namespace( completeNamespace );
		
		//if namespace is already in place, nothing happens
		if( typeof nspace.publish === 'function' ) {
			return nspace; //nothing to do, namespace already existing
		}
		
		//create the publish/subscribe/unsubscribe functions in the namespace
		nspace.publish = function( data ) { 
			//console.log( "publishing " + namespacedEvent );
			_publish( namespacedEvent, ( $.isArray(data) ? data : [data]) ); 
		};
		nspace.subscribe = function( callback ) { return _subscribe( namespacedEvent, callback ); };
		nspace.unsubscribe = function( handleFromSubscribe ) { return _unsubscribe( handleFromSubscribe ); };
		
		return nspace; //useful for chaining
	};
	
}(jQuery));;
namespace( 'brandx.utils' );

(function($){
	
	//pixel space taken by the browser chrome window
	var chrome = {
		height: 40,
		width: 2
	};
	
	function getScreenBasedOn( inwidth, inheight ) {
		var _scr = { availHeight: inheight - 100, availLeft: 0, availTop: 20, availWidth: inwidth, colorDepth: 24, height: inheight, left: 0, pixelDepth: 24, top: 0, width: inwidth };
		return _scr;
	}
	
	brandx.utils.Screen = {
		
		getScreenDimensions: function(){
			var _defaultScreen = getScreenBasedOn( 1024, 768 );
			if( screen ) {
				$.extend( _defaultScreen, screen );
			} 
			return _defaultScreen;
		},
		
		zoomAt: function( percentage, config ) {
			var _config = $.extend( { aspect:1.33 }, config );
			
			var dim = this.getScreenDimensions();
			dim.computedHeight = parseInt( dim.availHeight * (percentage/100), 10 );
			dim.computedWidth = parseInt( dim.computedHeight * _config.aspect, 10 );
			return dim;
		},
		
		center: function( dimensions, container ) {
			var pos,
				screen = this.getScreenDimensions(),
				context;

			context = { width: (container ? $(container).width() : screen.availWidth), height: (container ? $(container).height() : screen.availHeight ) };
			
			pos = { 
				left: parseInt( ( context.width - dimensions.width ) / 2, 10 ),
				top:  parseInt( ( context.height - dimensions.height ) / 2, 10 ) - chrome.height
			};
			
			//tolerance
			if( pos.top < 0 ) {
				pos.top = 0;
			}
			if( pos.left < 0 ) {
				pos.left = 0;
			}
			
			return pos;
		}
	};
	
}(jQuery));;
/**
* Utility class used for creating a KeepAlive heartbit to avoid session timeouts
*
* In order to use it, it's enough to instance this class (through create()) in the page you want to secure from session timeouts
* 
*  brandx.utils.session.KeepAlive.create();
*
* The create function can receive a configuration object with the following attributes:
*   timeout: <timeout to use in millisec>
*
* So, for example, to have a keep alive with a frequency of 10 seconds:
*
*  brandx.utils.session.KeepAlive.create( {timeout: 10000} );
*
* Note: The KeepAlive will normally NOT start if the user is not authenticated and the create() function will return a null object.
*       To start the keepAlive timer regardless of user status, pass the parameter "ignoreUserStatus: true"
*/
namespace( 'brandx.utils.session' );

brandx.events.require( "session.KeepAlive.Ticked" );
brandx.events.require( "session.KeepAlive.Success" );
brandx.events.require( "session.KeepAlive.Failure" );

(function($) {

	var DEFAULT_TIMEOUT_MILLIS = 25 * 60 * 1000;
	
	brandx.utils.session.KeepAlive = {

		/**
		* Create a new KeepAlive object for keeping the session alive
		* if the user is not authenticated, no keep alive is create and the function returns null.
		* Otherwise, a KeepAlive object is returned.
		*/
		create: function( keepAliveConfig ) {
			var timer = null,
				config;
				
			/*-----------------------------
			* privileged functions
			*------------------------------*/
			function _onTimer() {
				WebPlatformAccountServices.keepAlive( 
					function() {
						brandx.events.session.KeepAlive.Success.publish();
					},	//onSuccess
					function() {
						brandx.events.session.KeepAlive.Failure.publish();
					},	//onFailure
					function() {	//onComplete
						brandx.events.session.KeepAlive.Ticked.publish();
						//re-set the interval
						timer = setTimeout( _onTimer, config.timeout );
					}); 
			}
			
			function _start() {
				_stop();
				timer = setTimeout( _onTimer, config.timeout );

			}
			
			function _stop() {
				if( timer ) {
					clearTimeout( timer );
					timer = null;
				}
			}
			
			function _restart() {
				_stop();
				_start();
			}
			
			/*-----------------------------
			* main logic
			*------------------------------*/
			config = $.extend( { timeout: DEFAULT_TIMEOUT_MILLIS, ignoreUserStatus:false }, keepAliveConfig );
			
			if( !config.ignoreUserStatus && (typeof isAuthenticated === 'undefined' || !isAuthenticated()) ) {
				//user not authenticated or feature not available.
				return null;
			}
			
			//start the timer
			_start();
			
			//return the KeepAlive object instance
			return {
				stop: _stop,
				restart: _restart
			};

		}
	};
}(jQuery));;
/**
* Utility class used for creating a Generic timer
*
* In order to use it, it's enough to instance this class (through create()) in the page you want to use your timer, and give this
* instance a config object with the callback to be called (and other optional parameters)
* 
*  brandx.utils.IntervalTimer.create( { 
*		timeout: 10000,
*		callback: function() { },
*		startImmediately: true|false
*		scope: this-or-that //where to the "this" of the callback will point to ?
*	} );
*
* The create function can receive a configuration object with the following attributes:
*   timeout: <timeout to use in millisec>
*
*/
namespace( 'brandx.util' );
(function($) {

	var DEFAULT_TIMEOUT_MILLIS = 10 * 1000;
	
	brandx.utils.IntervalTimer = {
		/**
		* Create a new KeepAlive object for keeping the session alive
		* if the user is not authenticated, no keep alive is create and the function returns null.
		* Otherwise, a KeepAlive object is returned.
		*/
		create: function( timerConfig ) {
			var timer = null,
				config;
				
			/*-----------------------------
			* privileged functions
			*------------------------------*/
			function _callCallback() {
				if( typeof config.callback === 'function' ) {
					if( config.callback.call( ( config.scope ? config.scope : window ) ) === false ) {
						//stop the timer
						_stop();
						return;
					}
				}
			}
			function _onTimer() {
				//call the callback
				_callCallback();
				//re-set the interval
				_start();
			}
			
			function _start() {
				_stop();
				timer = setTimeout( _onTimer, config.timeout );
			}
			
			function _stop() {
				if( timer ) {
					clearTimeout( timer );
					timer = null;
				}
			}
			
			function _restart() {
				_start();
				
				if( config.startImmediately ) {
					_callCallback();
				}
			}
			
			/*-----------------------------
			* main logic
			*------------------------------*/
			config = $.extend( { timeout: DEFAULT_TIMEOUT_MILLIS, callback: function(){}, startImmediately:false }, timerConfig );
			
			if( config.startImmediately ) {
				_callCallback();
			}
			
			//start the timer
			_start();
			
			//return the KeepAlive object instance
			return {
				stop: _stop,
				restart: _restart
			};
		}
	};
}(jQuery));;
/*!
* Tim
*   github.com/premasagar/tim
*
*//*
    A tiny, secure JavaScript micro-templating script.
*//*

    by Premasagar Rose
        dharmafly.com

    license
        opensource.org/licenses/mit-license.php

    **

    creates global object
        tim

    **

    v0.3.0

*//*global window */

/*
    TODO:
    * a way to prevent a delimiter (e.g. ", ") appearing last in a loop template
    * Sorted constructor for auto-sorting arrays - used for parsers -> two parsers are added, one for identifying and parsing single-tokens and one for open/close tokens - the parsers then create two new Sorted instance, one for single-token plugins and one for open/close token plugins
*/

var tim = (function createTim(initSettings){
    "use strict";
    
    var settings = {
            start: "{{",
            end  : "}}",
            path : "[a-z0-9_][\\.a-z0-9_]*" // e.g. config.person.name
        },
        templates = {},
        filters = {},
        stopThisFilter, pattern, initialized, undef;
        
        
    /////
    

    // Update cached regex pattern
    function patternCache(){
        pattern = new RegExp(settings.start + "\\s*("+ settings.path +")\\s*" + settings.end, "gi");
    }
    
    // settingsCache: Get and set settings
    /*
        Example usage:
        settingsCache(); // get settings object
        settingsCache({start:"<%", end:"%>", attr:"id"}); // set new settings
    */
    function settingsCache(newSettings){
        var s;
    
        if (newSettings){
            for (s in newSettings){
                if (newSettings.hasOwnProperty(s)){
                    settings[s] = newSettings[s];
                }
            }
            patternCache();
        }
        return settings;
    }
        
    // Apply custom settings
    if (initSettings){
        settingsCache(initSettings);
    }
    else {
        patternCache();
    }
    
    
    /////
    
    
    // templatesCache: Get and set the templates cache object
    /*
        Example usage:
        templatesCache("foo"); // get template named "foo"
        templatesCache("foo", "bar"); // set template named "foo" to "bar"
        templatesCache("foo", false); // delete template named "foo"
        templatesCache({foo:"bar", blah:false}); // set multiple templates
        templatesCache(false); // delete all templates
    */
    function templatesCache(key, value){
        var t;
    
        switch (typeof key){
            case "string":
                if (value === undef){
                    return templates[key] || "";
                }
                else if (value === false){
                    delete templates[key];
                }
                else {
                    templates[key] = value;
                }
            break;
            
            case "object":
                for (t in key){
                    if (key.hasOwnProperty(t)){
                        templatesCache(t, key[t]);
                    }
                }
            break;
            
            case "boolean":
            if (!key){
                templates = {};
            }
            break;
        }
        return templates;
    }
    
    function extend(obj1, obj2){
        var key;
        for (key in obj2){
            if (obj2.hasOwnProperty(key)){
                obj1[key] = obj2[key];
            }
        }
        return obj1;
    }
    
    
    /////
    
    
    // FILTERS    
    function sortByPriority(a, b){
        return a[1] - b[1];
    }
    
    // Add filter to the stack
    function addFilter(filterName, fn, priority){
        var fns = filters[filterName];
        if (!fns){
            fns = filters[filterName] = [];
        }
        fns.push([fn, priority || 0]);
        fns.sort(sortByPriority);
        return fn;
    }
    
    function applyFilter(filterName, payload){
        var fns = filters[filterName],
            args, i, len, substituted;
            
        if (fns){
            args = [payload];
            i = 2;
            len = arguments.length;            
            for (; i < len; i++){
                args.push(arguments[i]);
            }
            
            i = 0;
            len = fns.length;
            for (; i < len; i++){
                args[0] = payload;
                substituted = fns[i][0].apply(null, args);
                if (payload !== undef && substituted !== undef){
                    payload = substituted;
                }
                if (stopThisFilter){
                    stopThisFilter = false;
                    break;
                }
            }
        }
        return payload;
    }
    
    // Router for adding and applying filters, for Tim API
    function filter(filterName, payload){
        return (typeof payload === "function" ? addFilter : applyFilter)
            .apply(null, arguments);
    }
    filter.stop = function(){
        stopThisFilter = true;
    };
    
    
    /////
    
    
    // Merge data into template
    /*  
        // simpler alternative, without support for iteration:
        template = template.replace(pattern, function(tag, token){
            return applyFilter("token", token, data, template);
        });
    */
    // TODO: all an array to be passed to tim(), so that the template is called for each element in it
    function substitute(template, data){
        var match, tag, token, substituted, startPos, endPos, templateStart, templateEnd, subTemplate, closeToken, closePos, key, loopData, loop;
    
        while((match = pattern.exec(template)) !== null) {
            token = match[1];
            substituted = applyFilter("token", token, data, template);
            startPos = match.index;
            endPos = pattern.lastIndex;
            templateStart = template.slice(0, startPos);
            templateEnd = template.slice(endPos);
            
            // If the final value is a function call it and use the returned
            // value in its place.
            if (typeof substituted === "function") {
                substituted = substituted.call(data);
            }
            
            if (typeof substituted !== "boolean" && typeof substituted !== "object"){
                template = templateStart + substituted + templateEnd;
            } else {
                subTemplate = "";
                closeToken = settings.start + "/" + token + settings.end;
                closePos = templateEnd.indexOf(closeToken);
                
                if (closePos >= 0){
                    templateEnd = templateEnd.slice(0, closePos);
                    if (typeof substituted === "boolean") {
                        subTemplate = substituted ? templateEnd : '';
                    } else {
                        for (key in substituted){
                            if (substituted.hasOwnProperty(key)){
                                pattern.lastIndex = 0;
                            
                                // Allow {{_key}} and {{_content}} in templates
                                loopData = extend({_key:key, _content:substituted[key]}, substituted[key]);
                                loopData = applyFilter("loopData", loopData, loop, token);
                                loop = tim(templateEnd, loopData);
                                subTemplate += applyFilter("loop", loop, token, loopData);
                            }
                        }
                        subTemplate = applyFilter("loopEnd", subTemplate, token, loopData);
                    }
                    template = templateStart + subTemplate + template.slice(endPos + templateEnd.length + closeToken.length);
                }
                else {
                    throw "tim: '" + token + "' not closed";
                }
            }
            
            pattern.lastIndex = 0;
        }
        return template;
    }
    
    
    // TIM - MAIN FUNCTION
    function tim(template, data){
        var templateLookup;
    
        // On first run, call init plugins
        if (!initialized){
            initialized = 1;        
            applyFilter("init");
        }
        template = applyFilter("templateBefore", template);
    
        // No template tags found in template
        if (template.indexOf(settings.start) < 0){
            // Is this a key for a cached template?
            templateLookup = templatesCache(template);
            if (templateLookup){
                template = templateLookup;
            }
        }
        template = applyFilter("template", template);
        
        // Substitute tokens in template
        if (template && data !== undef){
            template = substitute(template, data);
        }
        
        template = applyFilter("templateAfter", template);
        return template;
    }
    
    // Get and set settings, e.g. tim({attr:"id"});
    tim.settings = settingsCache;
    
    // Get and set cached templates
    tim.templates = templatesCache;
    
    // Create new Tim function, based on supplied settings, if any
    tim.parser = createTim;
    
    // Add new filters and trigger existing ones. Use tim.filter.stop() during processing, if required.
    tim.filter = filter;
    
    
    /////
    
    
    // dotSyntax default plugin: uses dot syntax to parse a data object for substitutions
    addFilter("token", function(token, data, tag){
        var path = token.split("."),
            len = path.length,
            dataLookup = data,
            i = 0;

        for (; i < len; i++){
            dataLookup = dataLookup[path[i]];
            
            // Property not found
            if (dataLookup === undef){
                throw "tim: '" + path[i] + "' not found" + (i ? " in " + tag : "");
            }
            
            // Return the required value
            if (i === len - 1){
                return dataLookup;
            }
        }
    });
    
    
    /////
    
    
    // Dom plugin: finds micro-templates in <script>'s in the DOM
    // This block of code can be removed if unneeded - e.g. with server-side JS
    // Default: <script type="text/tim" class="foo">{{TEMPLATE}}</script>
    if (window && window.document){
        tim.dom = function(domSettings){
            domSettings = domSettings || {};
            
            var type = domSettings.type || settings.type || "text/tim",
                attr = domSettings.attr || settings.attr || "class",
                document = window.document,
                hasQuery = !!document.querySelectorAll,
                elements = hasQuery ?
                    document.querySelectorAll(
                        "script[type='" + type + "']"
                    ) :
                    document.getElementsByTagName("script"),
                i = 0,
                len = elements.length,
                elem, key,
                templatesInDom = {};
                
            for (; i < len; i++){
                elem = elements[i];
                // Cannot access "class" using el.getAttribute()
                key = attr === "class" ? elem.className : elem.getAttribute(attr);
                if (key && (hasQuery || elem.type === type)){
                    templatesInDom[key] = elem.innerHTML;
                }
            }
            
            templatesCache(templatesInDom);
            return templatesInDom;
        };
        
        addFilter("init", function(){
            tim.dom();
        });
    }
    
    return tim;
}());

/*jslint browser: true, onevar: true, undef: true, eqeqeq: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: true */
;
brandx.events.require( 'modal.WindowClosed' );
brandx.events.require( 'modal.WindowOpened' );

/*
 * SimpleModal 1.4.1 - jQuery Plugin
 * http://www.ericmmartin.com/projects/simplemodal/
 * Copyright (c) 2010 Eric Martin (http://twitter.com/ericmmartin)
 * Dual licensed under the MIT and GPL licenses
 * Revision: $Id: jquery.simplemodal.js 261 2010-11-05 21:16:20Z emartin24 $
 */

/**
 * SimpleModal is a lightweight jQuery plugin that provides a simple
 * interface to create a modal dialog.
 *
 * The goal of SimpleModal is to provide developers with a cross-browser
 * overlay and container that will be populated with data provided to
 * SimpleModal.
 *
 * There are two ways to call SimpleModal:
 * 1) As a chained function on a jQuery object, like $('#myDiv').modal();.
 * This call would place the DOM object, #myDiv, inside a modal dialog.
 * Chaining requires a jQuery object. An optional options object can be
 * passed as a parameter.
 *
 * @example $('<div>my data</div>').modal({options});
 * @example $('#myDiv').modal({options});
 * @example jQueryObject.modal({options});
 *
 * 2) As a stand-alone function, like $.modal(data). The data parameter
 * is required and an optional options object can be passed as a second
 * parameter. This method provides more flexibility in the types of data
 * that are allowed. The data could be a DOM object, a jQuery object, HTML
 * or a string.
 *
 * @example $.modal('<div>my data</div>', {options});
 * @example $.modal('my data', {options});
 * @example $.modal($('#myDiv'), {options});
 * @example $.modal(jQueryObject, {options});
 * @example $.modal(document.getElementById('myDiv'), {options});
 *
 * A SimpleModal call can contain multiple elements, but only one modal
 * dialog can be created at a time. Which means that all of the matched
 * elements will be displayed within the modal container.
 *
 * SimpleModal internally sets the CSS needed to display the modal dialog
 * properly in all browsers, yet provides the developer with the flexibility
 * to easily control the look and feel. The styling for SimpleModal can be
 * done through external stylesheets, or through SimpleModal, using the
 * overlayCss, containerCss, and dataCss options.
 *
 * SimpleModal has been tested in the following browsers:
 * - IE 6, 7, 8, 9
 * - Firefox 2, 3, 4
 * - Opera 9, 10
 * - Safari 3, 4, 5
 * - Chrome 1, 2, 3, 4, 5, 6
 *
 * @name SimpleModal
 * @type jQuery
 * @requires jQuery v1.2.4
 * @cat Plugins/Windows and Overlays
 * @author Eric Martin (http://ericmmartin.com)
 * @version 1.4.1
 */
;(function ($) {
	var ie6 = $.browser.msie && parseInt($.browser.version) === 6 && typeof window['XMLHttpRequest'] !== 'object',
		ie7 = $.browser.msie && parseInt($.browser.version) === 7,
		ieQuirks = null,
		w = [];

	function hasXEvents() {
		return typeof brandx !== 'undefined' && typeof brandx.events !== 'undefined';
	}
	
	/*
	 * Create and display a modal dialog.
	 *
	 * @param {string, object} data A string, jQuery object or DOM object
	 * @param {object} [options] An optional object containing options overrides
	 */
	$.modal = function (data, options) {
		return $.modal.impl.init(data, options);
	};

	/*
	 * Close the modal dialog.
	 */
	$.modal.close = function () {
		$.modal.impl.close.apply( $.modal.impl, arguments);
	};

	/*
	 * Set focus on first or last visible input in the modal dialog. To focus on the last
	 * element, call $.modal.focus('last'). If no input elements are found, focus is placed
	 * on the data wrapper element.
	 */
	$.modal.focus = function (pos) {
		$.modal.impl.focus(pos);
	};

	/*
	 * Determine and set the dimensions of the modal dialog container.
	 * setPosition() is called if the autoPosition option is true.
	 */
	$.modal.setContainerDimensions = function () {
		$.modal.impl.setContainerDimensions();
	};

	/*
	 * Re-position the modal dialog.
	 */
	$.modal.setPosition = function () {
		$.modal.impl.setPosition();
	};

	/*
	 * Update the modal dialog. If new dimensions are passed, they will be used to determine
	 * the dimensions of the container.
	 *
	 * setContainerDimensions() is called, which in turn calls setPosition(), if enabled.
	 * Lastly, focus() is called is the focus option is true.
	 */
	$.modal.update = function (height, width) {
		$.modal.impl.update(height, width);
	};

	/*
	 * Chained function to create a modal dialog.
	 *
	 * @param {object} [options] An optional object containing options overrides
	 */
	$.fn.modal = function (options) {
		return $.modal.impl.init(this, options);
	};

	/*
	 * SimpleModal default options
	 *
	 * appendTo:		(String:'body') The jQuery selector to append the elements to. For .NET, use 'form'.
	 * focus:			(Boolean:true) Focus in the first visible, enabled element?
	 * opacity:			(Number:50) The opacity value for the overlay div, from 0 - 100
	 * overlayId:		(String:'simplemodal-overlay') The DOM element id for the overlay div
	 * overlayCss:		(Object:{}) The CSS styling for the overlay div
	 * containerId:		(String:'simplemodal-container') The DOM element id for the container div
	 * containerCss:	(Object:{}) The CSS styling for the container div
	 * dataId:			(String:'simplemodal-data') The DOM element id for the data div
	 * dataCss:			(Object:{}) The CSS styling for the data div
	 * minHeight:		(Number:null) The minimum height for the container
	 * minWidth:		(Number:null) The minimum width for the container
	 * maxHeight:		(Number:null) The maximum height for the container. If not specified, the window height is used.
	 * maxWidth:		(Number:null) The maximum width for the container. If not specified, the window width is used.
	 * autoResize:		(Boolean:false) Automatically resize the container if it exceeds the browser window dimensions?
	 * autoPosition:	(Boolean:true) Automatically position the container upon creation and on window resize?
	 * zIndex:			(Number: 1000) Starting z-index value
	 * close:			(Boolean:true) If true, closeHTML, escClose and overClose will be used if set.
	 							If false, none of them will be used.
	 * closeHTML:		(String:'<a class="modalCloseImg" title="Close"></a>') The HTML for the default close link.
								SimpleModal will automatically add the closeClass to this element.
	 * closeClass:		(String:'simplemodal-close') The CSS class used to bind to the close event
	 * escClose:		(Boolean:true) Allow Esc keypress to close the dialog?
	 * overlayClose:	(Boolean:false) Allow click on overlay to close the dialog?
	 * position:		(Array:null) Position of container [top, left]. Can be number of pixels or percentage
	 * persist:			(Boolean:false) Persist the data across modal calls? Only used for existing
								DOM elements. If true, the data will be maintained across modal calls, if false,
								the data will be reverted to its original state.
	 * modal:			(Boolean:true) User will be unable to interact with the page below the modal or tab away from the dialog.
								If false, the overlay, iframe, and certain events will be disabled allowing the user to interact
								with the page below the dialog.
	 * onOpen:			(Function:null) The callback function used in place of SimpleModal's open
	 * onShow:			(Function:null) The callback function used after the modal dialog has opened
	 * onClose:			(Function:null) The callback function used in place of SimpleModal's close
	 */
	$.modal.defaults = {
		appendTo: 'body',
		focus: true,
		opacity: 50,
		overlayId: 'simplemodal-overlay',
		overlayCss: {},
		containerId: 'simplemodal-container',
		containerCss: {},
		dataId: 'simplemodal-data',
		dataCss: {},
		minHeight: null,
		minWidth: null,
		maxHeight: null,
		maxWidth: null,
		autoResize: false,
		autoPosition: true,
		zIndex: 1000,
		close: true,
		closeHTML: '<a class="modalCloseImg" title="Close"></a>',
		closeClass: 'simplemodal-close',
		escClose: true,
		overlayClose: false,
		position: null,
		persist: false,
		modal: true,
		onOpen: null,
		onShow: null,
		onClose: null
	};

	/*
	 * Main modal object
	 * o = options
	 */
	$.modal.impl = {
		/*
		 * Contains the modal dialog elements and is the object passed
		 * back to the callback (onOpen, onShow, onClose) functions
		 */
		d: {},
		/*
		 * Initialize the modal dialog
		 */
		init: function (data, options) {
			var s = this;

			// don't allow multiple calls
			if (s.d.data) {
				return false;
			}

			// $.boxModel is undefined if checked earlier
			ieQuirks = $.browser.msie && !$.boxModel;

			// merge defaults and user options
			s.o = $.extend({}, $.modal.defaults, options);

			// keep track of z-index
			s.zIndex = s.o.zIndex;

			// set the on callback flag
			s.occb = false;

			// determine how to handle the data based on its type
			if (typeof data === 'object') {
				// convert DOM object to a jQuery object
				data = data instanceof jQuery ? data : $(data);
				s.d.placeholder = false;

				// if the object came from the DOM, keep track of its parent
				if (data.parent().parent().size() > 0) {
					data.before($('<span></span>')
						.attr('id', 'simplemodal-placeholder')
						.css({display: 'none'}));

					s.d.placeholder = true;
					s.display = data.css('display');

					// persist changes? if not, make a clone of the element
					if (!s.o.persist) {
						s.d.orig = data.clone(true);
					}
				}
			}
			else if (typeof data === 'string' || typeof data === 'number') {
				// just insert the data as innerHTML
				data = $('<div></div>').html(data);
			}
			else {
				// unsupported data type!
				alert('SimpleModal Error: Unsupported data type: ' + typeof data);
				return s;
			}

			// create the modal overlay, container and, if necessary, iframe
			s.create(data);
			data = null;

			// display the modal dialog
			s.open();

			// useful for adding events/manipulating data in the modal dialog
			if ($.isFunction(s.o.onShow)) {
				s.o.onShow.apply(s, [s.d]);
			}

			// don't break the chain =)
			return s;
		},
		/*
		 * Create and add the modal overlay and container to the page
		 */
		create: function (data) {
			var s = this;

			// get the window properties
			w = s.getDimensions();

			// add an iframe to prevent select options from bleeding through
			if (s.o.modal && ie6) {
				s.d.iframe = $('<iframe src="javascript:false;"></iframe>')
					.css($.extend(s.o.iframeCss, {
						display: 'none',
						opacity: 0,
						position: 'fixed',
						height: w[0],
						width: w[1],
						zIndex: s.o.zIndex,
						top: 0,
						left: 0
					}))
					.appendTo(s.o.appendTo);
			}

			// create the overlay
			s.d.overlay = $('<div></div>')
				.attr('id', s.o.overlayId)
				.addClass('simplemodal-overlay')
				.css($.extend(s.o.overlayCss, {
					display: 'none',
					opacity: s.o.opacity / 100,
					height: s.o.modal ? w[0] : 0,
					width: s.o.modal ? w[1] : 0,
					position: 'fixed',
					left: 0,
					top: 0,
					zIndex: s.o.zIndex + 1
				}))
				.appendTo(s.o.appendTo);

			// create the container
			s.d.container = $('<div></div>')
				.attr('id', s.o.containerId)
				.addClass('simplemodal-container')
				.css($.extend(s.o.containerCss, {
					display: 'none',
					position: 'fixed',
					zIndex: s.o.zIndex + 2
				}))
				.append(s.o.close && s.o.closeHTML
					? $(s.o.closeHTML).addClass(s.o.closeClass)
					: '')
				.appendTo(s.o.appendTo);

			s.d.wrap = $('<div></div>')
				.attr('tabIndex', -1)
				.addClass('simplemodal-wrap')
				.css({height: '100%', outline: 0, width: '100%'})
				.appendTo(s.d.container);

			// add styling and attributes to the data
			// append to body to get correct dimensions, then move to wrap
			s.d.data = data
				.attr('id', data.attr('id') || s.o.dataId)
				.addClass('simplemodal-data')
				.css($.extend(s.o.dataCss, {
						display: 'none'
				}))
				.appendTo('body');
			data = null;

			s.setContainerDimensions();
			s.d.data.appendTo(s.d.wrap);

			// fix issues with IE
			if (ie6 || ieQuirks) {
				s.fixIE();
			}
		},
		/*
		 * Bind events
		 */
		bindEvents: function () {
			var s = this;

			// bind the close event to any element with the closeClass class
			$('.' + s.o.closeClass).bind('click.simplemodal', function (e) {
				e.preventDefault();
				s.close();
			});

			// bind the overlay click to the close function, if enabled
			if (s.o.modal && s.o.close && s.o.overlayClose) {
				s.d.overlay.bind('click.simplemodal', function (e) {
					e.preventDefault();
					s.close();
				});
			}

			// bind keydown events
			$(document).bind('keydown.simplemodal', function (e) {
				if (s.o.modal && e.keyCode === 9) { // TAB
					s.watchTab(e);
				}
				else if ((s.o.close && s.o.escClose) && e.keyCode === 27) { // ESC
					e.preventDefault();
					s.close();
				}
			});

			// update window size
			$(window).bind('resize.simplemodal', function () {
				// redetermine the window width/height
				w = s.getDimensions();

				// reposition the dialog
				s.o.autoResize ? s.setContainerDimensions() : s.o.autoPosition && s.setPosition();

				if (ie6 || ieQuirks) {
					s.fixIE();
				}
				else if (s.o.modal) {
					// update the iframe & overlay
					s.d.iframe && s.d.iframe.css({height: w[0], width: w[1]});
					s.d.overlay.css({height: w[0], width: w[1]});
				}
			});
		},
		/*
		 * Unbind events
		 */
		unbindEvents: function () {
			$('.' + this.o.closeClass).unbind('click.simplemodal');
			$(document).unbind('keydown.simplemodal');
			$(window).unbind('resize.simplemodal');
			this.d.overlay.unbind('click.simplemodal');
		},
		/*
		 * Fix issues in IE6 and IE7 in quirks mode
		 */
		fixIE: function () {
			var s = this, p = s.o.position;

			// simulate fixed position - adapted from BlockUI
			$.each([s.d.iframe || null, !s.o.modal ? null : s.d.overlay, s.d.container], function (i, el) {
				if (el) {
					var bch = 'document.body.clientHeight', bcw = 'document.body.clientWidth',
						bsh = 'document.body.scrollHeight', bsl = 'document.body.scrollLeft',
						bst = 'document.body.scrollTop', bsw = 'document.body.scrollWidth',
						ch = 'document.documentElement.clientHeight', cw = 'document.documentElement.clientWidth',
						sl = 'document.documentElement.scrollLeft', st = 'document.documentElement.scrollTop',
						s = el[0].style;

					s.position = 'absolute';
					if (i < 2) {
						s.removeExpression('height');
						s.removeExpression('width');
						s.setExpression('height','' + bsh + ' > ' + bch + ' ? ' + bsh + ' : ' + bch + ' + "px"');
						s.setExpression('width','' + bsw + ' > ' + bcw + ' ? ' + bsw + ' : ' + bcw + ' + "px"');
					}
					else {
						var te, le;
						if (p && p.constructor === Array) {
							var top = p[0]
								? typeof p[0] === 'number' ? p[0].toString() : p[0].replace(/px/, '')
								: el.css('top').replace(/px/, '');
							te = top.indexOf('%') === -1
								? top + ' + (t = ' + st + ' ? ' + st + ' : ' + bst + ') + "px"'
								: parseInt(top.replace(/%/, '')) + ' * ((' + ch + ' || ' + bch + ') / 100) + (t = ' + st + ' ? ' + st + ' : ' + bst + ') + "px"';

							if (p[1]) {
								var left = typeof p[1] === 'number' ? p[1].toString() : p[1].replace(/px/, '');
								le = left.indexOf('%') === -1
									? left + ' + (t = ' + sl + ' ? ' + sl + ' : ' + bsl + ') + "px"'
									: parseInt(left.replace(/%/, '')) + ' * ((' + cw + ' || ' + bcw + ') / 100) + (t = ' + sl + ' ? ' + sl + ' : ' + bsl + ') + "px"';
							}
						}
						else {
							te = '(' + ch + ' || ' + bch + ') / 2 - (this.offsetHeight / 2) + (t = ' + st + ' ? ' + st + ' : ' + bst + ') + "px"';
							le = '(' + cw + ' || ' + bcw + ') / 2 - (this.offsetWidth / 2) + (t = ' + sl + ' ? ' + sl + ' : ' + bsl + ') + "px"';
						}
						s.removeExpression('top');
						s.removeExpression('left');
						s.setExpression('top', te);
						s.setExpression('left', le);
					}
				}
			});
		},
		/*
		 * Place focus on the first or last visible input
		 */
		focus: function (pos) {
			var s = this, p = pos && $.inArray(pos, ['first', 'last']) !== -1 ? pos : 'first';

			// focus on dialog or the first visible/enabled input element
			var input = $(':input:enabled:visible:' + p, s.d.wrap);
			setTimeout(function () {
				input.length > 0 ? input.focus() : s.d.wrap.focus();
			}, 10);
		},
		getDimensions: function () {
			var el = $(window);

			// fix a jQuery/Opera bug with determining the window height
			var h = $.browser.opera && $.browser.version > '9.5' && $.fn.jquery < '1.3'
						|| $.browser.opera && $.browser.version < '9.5' && $.fn.jquery > '1.2.6'
				? el[0].innerHeight : el.height();

			return [h, el.width()];
		},
		getVal: function (v, d) {
			return v ? (typeof v === 'number' ? v
					: v === 'auto' ? 0
					: v.indexOf('%') > 0 ? ((parseInt(v.replace(/%/, '')) / 100) * (d === 'h' ? w[0] : w[1]))
					: parseInt(v.replace(/px/, '')))
				: null;
		},
		/*
		 * Update the container. Set new dimensions, if provided.
		 * Focus, if enabled. Re-bind events.
		 */
		update: function (height, width) {
			var s = this;

			// prevent update if dialog does not exist
			if (!s.d.data) {
				return false;
			}

			// reset orig values
			s.d.origHeight = s.getVal(height, 'h');
			s.d.origWidth = s.getVal(width, 'w');

			// hide data to prevent screen flicker
			s.d.data.hide();
			height && s.d.container.css('height', height);
			width && s.d.container.css('width', width);
			s.setContainerDimensions();
			s.d.data.show();
			s.o.focus && s.focus();

			// rebind events
			s.unbindEvents();
			s.bindEvents();
		},
		setContainerDimensions: function () {
			var s = this,
				badIE = ie6 || ie7;

			// get the dimensions for the container and data
			var ch = s.d.origHeight ? s.d.origHeight : $.browser.opera ? s.d.container.height() : s.getVal(badIE ? s.d.container[0].currentStyle['height'] : s.d.container.css('height'), 'h'),
				cw = s.d.origWidth ? s.d.origWidth : $.browser.opera ? s.d.container.width() : s.getVal(badIE ? s.d.container[0].currentStyle['width'] : s.d.container.css('width'), 'w'),
				dh = s.d.data.outerHeight(true), dw = s.d.data.outerWidth(true);

			s.d.origHeight = s.d.origHeight || ch;
			s.d.origWidth = s.d.origWidth || cw;

			// mxoh = max option height, mxow = max option width
			var mxoh = s.o.maxHeight ? s.getVal(s.o.maxHeight, 'h') : null,
				mxow = s.o.maxWidth ? s.getVal(s.o.maxWidth, 'w') : null,
				mh = mxoh && mxoh < w[0] ? mxoh : w[0],
				mw = mxow && mxow < w[1] ? mxow : w[1];

			// moh = min option height
			var moh = s.o.minHeight ? s.getVal(s.o.minHeight, 'h') : 'auto';
			if (!ch) {
				if (!dh) {ch = moh;}
				else {
					if (dh > mh) {ch = mh;}
					else if (s.o.minHeight && moh !== 'auto' && dh < moh) {ch = moh;}
					else {ch = dh;}
				}
			}
			else {
				ch = s.o.autoResize && ch > mh ? mh : ch < moh ? moh : ch;
			}

			// mow = min option width
			var mow = s.o.minWidth ? s.getVal(s.o.minWidth, 'w') : 'auto';
			if (!cw) {
				if (!dw) {cw = mow;}
				else {
					if (dw > mw) {cw = mw;}
					else if (s.o.minWidth && mow !== 'auto' && dw < mow) {cw = mow;}
					else {cw = dw;}
				}
			}
			else {
				cw = s.o.autoResize && cw > mw ? mw : cw < mow ? mow : cw;
			}

			s.d.container.css({height: ch, width: cw});
			s.d.wrap.css({overflow: (dh > ch || dw > cw) ? 'auto' : 'visible'});
			s.o.autoPosition && s.setPosition();
		},
		setPosition: function () {
			var s = this, top, left,
				hc = (w[0]/2) - (s.d.container.outerHeight(true)/2),
				vc = (w[1]/2) - (s.d.container.outerWidth(true)/2);

			if (s.o.position && Object.prototype.toString.call(s.o.position) === '[object Array]') {
				top = s.o.position[0] || hc;
				left = s.o.position[1] || vc;
			} else {
				top = hc;
				left = vc;
			}
			s.d.container.css({left: left, top: top});
		},
		watchTab: function (e) {
			var s = this;

			if ($(e.target).parents('.simplemodal-container').length > 0) {
				// save the list of inputs
				s.inputs = $(':input:enabled:visible:first, :input:enabled:visible:last', s.d.data[0]);

				// if it's the first or last tabbable element, refocus
				if ((!e.shiftKey && e.target === s.inputs[s.inputs.length -1]) ||
						(e.shiftKey && e.target === s.inputs[0]) ||
						s.inputs.length === 0) {
					e.preventDefault();
					var pos = e.shiftKey ? 'last' : 'first';
					s.focus(pos);
				}
			}
			else {
				// might be necessary when custom onShow callback is used
				e.preventDefault();
				s.focus();
			}
		},
		/*
		 * Open the modal dialog elements
		 * - Note: If you use the onOpen callback, you must "show" the
		 *	        overlay and container elements manually
		 *         (the iframe will be handled by SimpleModal)
		 */
		open: function () {
			var s = this;
			// display the iframe
			s.d.iframe && s.d.iframe.show();

			if ($.isFunction(s.o.onOpen)) {
				// execute the onOpen callback
				s.o.onOpen.apply(s, [s.d]);
				
				if( hasXEvents ) { brandx.events.modal.WindowOpened.publish(); }
			}
			else {
				// display the remaining elements
				s.d.overlay.show();
				s.d.container.show();
				s.d.data.show();
			}

			s.o.focus && s.focus();
			
			if( $.isFunction( s.o.afterOpen ) ) {
				s.o.afterOpen.apply( s, [s.d] );
			}
			
			//if we have events enables, let's use them!
			if( hasXEvents ) { brandx.events.modal.WindowOpened.publish(); }

			// bind default events
			s.bindEvents();
		},
		/*
		 * Close the modal dialog
		 * - Note: If you use an onClose callback, you must remove the
		 *         overlay, container and iframe elements manually
		 *
		 * @param {boolean} external Indicates whether the call to this
		 *     function was internal or external. If it was external, the
		 *     onClose callback will be ignored
		 */
		close: function () {
			var s = this;
			var callback = (arguments.length > 0 ? Array.prototype.slice.call( arguments )[0] : null);
			// prevent close when dialog does not exist
			if (!s.d.data) {
				return false;
			}

			// remove the default events
			s.unbindEvents();

			if ($.isFunction(s.o.onClose) && !s.occb) {
				// set the onClose callback flag
				s.occb = true;

				// execute the onClose callback
				s.o.onClose.apply(s, [s.d]);

				if( hasXEvents ) { brandx.events.modal.WindowClosed.publish(); }
				
			}
			else {
				// if the data came from the DOM, put it back
				if (s.d.placeholder) {
					var ph = $('#simplemodal-placeholder');
					// save changes to the data?
					if (s.o.persist) {
						// insert the (possibly) modified data back into the DOM
						ph.replaceWith(s.d.data.removeClass('simplemodal-data').css('display', s.display));
					}
					else {
						// remove the current and insert the original,
						// unmodified data back into the DOM
						s.d.data.hide().remove();
						ph.replaceWith(s.d.orig);
					}
				}
				else {
					// otherwise, remove it
					s.d.data.hide().remove();
				}

				// remove the remaining elements
				s.d.container.hide().remove();
				s.d.overlay.hide();
				s.d.iframe && s.d.iframe.hide().remove();
				setTimeout(function(){
					// opera work-around
					s.d.overlay.remove();

					// reset the dialog object
					s.d = {};
					
					//call the passed in callback, if any
					if( callback && typeof callback === 'function' ) {
						//call the callback to notify the end of the close event
						callback();
						
						//if we have events enables, let's use them!
						if( hasXEvents ) { brandx.events.modal.WindowClosed.publish(); }
					}
				}, 10);
			}
		}
	};
})(jQuery);
;
/*	SWFObject v2.2 <http://code.google.com/p/swfobject/> 
	is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();;
var UserProfile = {
  
    userId : 0,
    userName : '',
    balance : 0,
    currency : 'USD',
    currencySymbol : 'US$',
    messageCount : 0,
    email : '',
    addressLine1 : '',
    addressLine2 : '',
    city : '',
    state : '',
    zipcode : '',
    country : '',
    primaryPhone : '',
    primaryPhoneUse : '',
  
    getUserProfile : function () {
        if(isAuthenticated()) {
            WebPlatformAccountServices.getProfile(UserProfile.accountProfileSuccess, UserProfile.serviceError, null);
        }
    },
    
    accountProfileSuccess : function (data, textStatus, jqXHR) {
        UserProfile.email = data.email;
        UserProfile.addressLine1 = data.addressLine1;
        UserProfile.addressLine2 = data.addressLine2;
        UserProfile.city = data.city;
        UserProfile.state = data.state;
        UserProfile.zipcode  = data.zipcode;
        UserProfile.country = data.country;
        UserProfile.primaryPhone = data.primaryPhone;
        UserProfile.primaryPhoneUse = data.primaryPhoneUse;
        
        UserProfile.getAccountSummary();
    },
    
    getAccountSummary : function() {
        if(isAuthenticated()) {
            WebPlatformAccountServices.getAccountSummary(UserProfile.accountSummarySuccess, UserProfile.serviceError, null);
        }
    },
    
    accountSummarySuccess : function (data, textStatus, jqXHR) {
        UserProfile.userId = data.userId;
        UserProfile.userName = data.userName;
        UserProfile.balance = data.balance;
        UserProfile.currency = data.currency;
        UserProfile.currencySymbol = UserProfile.mapCurrencyCodeToCurrencySymbol(data.currency);
        UserProfile.messageCount = data.messageCount;
        
        WebPlatformAccountServicesEvents.triggerUserProfileReadyEvent();
    },
    
    getAccountBalance : function() {
        if(isAuthenticated()) {
            WebPlatformAccountServices.getAccountSummary(UserProfile.accountBalanceSuccess, UserProfile.serviceError, null);
        }
    },
    
    accountBalanceSuccess : function (data, textStatus, jqXHR) {
        if(data.balance != UserProfile.balance) {
            UserProfile.balance = data.balance;
            var formattedBalance = UserProfile.transformNumberIntoCurrencyFormat(data.balance);
            WebPlatformAccountServicesEvents.triggerBalanceChangedEvent(formattedBalance);
        }
    },
    
    mapCurrencyCodeToCurrencySymbol : function (currencyCode) {
        if (currencyCode == "USD") {
            return "US$";
        } else if (currencyCode == "EUR") {
            return "EU€";
        } else if (currencyCode == "GBP") {
            return "GB£";
        } else if (currencyCode == "CAD") {
            return "CA$";
        } else if (currencyCode == "ZAR") {
            return "ZAR";
        }
    },
    
    transformNumberIntoCurrencyFormat : function(num) {
        if(isNaN(num) || num === '' || num === null) {
            return num;
        } else {
            return parseFloat(num / 100).toFixed(2);
        }
    },
    
    serviceError : function (data, textStatus, jqXHR) {
        var errorCode = data.status;
        
        if(errorCode == 401 || errorCode == 503) {
            // Session has expired, redirect user to session expired url
            Login.redirectToSessionExpiredURL();
        }
    },
    
    /*
     * GETTER Methods
     */
    getUserId : function () {
        return UserProfile.userId;
    },
    
    getUserName : function () {
        return UserProfile.userName;
    },
    
    getBalance : function () {
        return UserProfile.balance;
    },
    
    getFormattedBalance : function (){
        return UserProfile.transformNumberIntoCurrencyFormat(UserProfile.balance);
    },
    
    getCurrency : function () {
        return UserProfile.currency;
    },
    
    getCurrencySymbol : function () {
        return UserProfile.currencySymbol;
    },
    
    getMessageCount : function () {
        return UserProfile.messageCount;
    },
    
    getEmail : function () {
        return UserProfile.email;
    },
    
    getAddressLine1 : function () {
        return UserProfile.addressLine1;
    },
    
    getAddressLine2 : function () {
        return UserProfile.addressLine2;
    },
    
    getCity : function () {
        return UserProfile.city;
    },
    
    getState : function () {
        return UserProfile.state;
    },
    
    getZipcode : function () {
        return UserProfile.zipcode;
    },
    
    getCountry : function () {
        return UserProfile.country;
    },
    
    getPrimaryPhone : function () {
        return UserProfile.primaryPhone;
    },
    
    getPrimaryPhoneUse : function () {
        return UserProfile.primaryPhoneUse;
    }
};;
var TimeZone = {
    
    defaultTimeZone : 26,
    timeZoneList : new Array(),
    currentTimeZone : 26,
  
    init : function () {
        TimeZone.createDefaultTimeZoneData();
        TimeZone.createOnTimezoneChangedEventListener();
        WebPlatformWebsiteServices.getTimezones(TimeZone.saveTheListOfTimeZones, TimeZone.timeZoneDataIsUnavailable, TimeZone.afterGettingTheTimeZones);
    },
    
    createOnTimezoneChangedEventListener : function () {
        WebPlatformAccountServicesEvents.bindToTimeZoneChangedEvent(TimeZone.timeZoneHasChanged);
    },
    
    timeZoneHasChanged : function () {
		    TimeZone.updateTheHeaderClock();        
    },
    
    timeZoneDataIsUnavailable : function () {
        TimeZone.createDefaultTimeZoneData();
    },
    
    createDefaultTimeZoneData : function () {
        TimeZone.currentTimeZone = TimeZone.defaultTimeZone;
        newTimeZone = new TimeZone.timeZoneObject("EST", "Eastern Standard Time", "-5");
        TimeZone.timeZoneList[TimeZone.defaultTimeZone] = newTimeZone;
    },
    
    afterGettingTheTimeZones : function () {        
        TimeZone.startTheHeaderClock();
        TimeZone.updateTheHeaderClock();
    },
    
    userIsLoggedIn : function () {
        TimeZone.getUsersTimeZoneFromService();
        TimeZone.buildTimeZoneSelector();
        TimeZone.setupSavingUsersTimezoneUponChange();
        TimeZone.showTimeZoneList();
    },
    
    userIsNotLoggedIn : function() {
        TimeZone.getTimezoneFromTheCookie();
        TimeZone.showSignInOrJoinMessage();
    },
    
    getUsersTimeZoneFromService : function () {
        WebPlatformAccountServices.getAccountPreferredTimezone(TimeZone.saveUsersPreferredTimezone, null, null);
    },
    
    saveUsersPreferredTimezone : function (data, textStatus, jqXHR) {
        jQuery("select#timezone").val(data.preferenceOptionId);
        TimeZone.currentTimeZone = data.preferenceOptionId;
        TimeZone.updateTimeZoneCodeInToggler();
        WebPlatformAccountServicesEvents.triggerTimeZoneChangedEvent();
    },
    
    updateTimeZoneCodeInToggler : function () {
        jQuery('#timeZoneCodeHolder').html(TimeZone.getTimeZoneCode);
    },
    
    buildTimeZoneSelector : function () {
        var listOfTimezones = '';
        if(TimeZone.timeZoneList.length == 0)  {
            listOfTimezones = '<li><a rel="nofollow" href="#">No Timezones</a></li>';
        } else {
            var addedFirstClass = ' class="first"';
            for(i = 1; i < TimeZone.timeZoneList.length; i++) {
                listOfTimezones += '<li' + addedFirstClass + '><a rel="nofollow" id="tz-' + i + '" href="#">' + TimeZone.timeZoneList[i].name + '</a></li>';
                addedFirstClass = '';
            }
        }

        jQuery('#timeZoneSelector div.viewport ul.overview').html(listOfTimezones);
    },
    
    setupSavingUsersTimezoneUponChange : function () {
        jQuery('#timeZoneSelector li a').unbind('click').click(function() {
            var preferenceOptionId = jQuery(this).attr('id').substring(3);
            accountUpdateTimezoneObject = new TimeZone.accountUpdateTimezoneDTO(preferenceOptionId);
            WebPlatformAccountServices.accountUpdateTimezone(accountUpdateTimezoneObject, TimeZone.updateUsersPreferredTimeZone, null, null);
        });
    },

    accountUpdateTimezoneDTO : function (preferredTimezoneID) {
        this.preferenceTypeId = "61";
        this.preferenceOptionId = preferredTimezoneID;
    },

    updateUsersPreferredTimeZone : function (data, textStatus, jqXHR) {
        if(data.success) {
            jQuery("#selectWrapper").hide();
            TimeZone.getUsersTimeZoneFromService();            
        }
    },
    
    showTimeZoneList : function () {
        jQuery('#selectTimeZone').show();
        jQuery('#timeZoneSelector').show();
        jQuery('#timeZoneNotLoggedIn').hide();
    },
    
    getTimezoneFromTheCookie : function() {
        var cookieValue = jQuery.cookie('ACCTIMEZONE');
        if (cookieValue != null && TimeZone.timeZoneList[cookieValue] != undefined) {
          TimeZone.currentTimeZone = cookieValue;
        }
    },
    
    showSignInOrJoinMessage : function () {
        jQuery('#timeZoneNotLoggedIn').show();
        jQuery('#selectTimeZone').hide();
        jQuery('#timeZoneSelector').hide();
    },
        
    startTheHeaderClock : function () {
        WebPlatformEvents.createTimer(1000, function(){ TimeZone.updateTheHeaderClock(); });
    },
    
    updateTheHeaderClock : function () {
        var usersLocalTime = TimeZone.getTimeWithTimeZoneOffset(new Date().getTime());
        TimeZone.updateClockDisplay(usersLocalTime);
    },
    
    updateClockDisplay : function (currentTimeInSeconds) {
        var currentTimeDate = new Date(currentTimeInSeconds);
        var displayedDate = dateFormat(currentTimeDate, "ddd mmm dd yyyy HH:MM:ss", true);
        jQuery('#currentTimeHolder').html(displayedDate);
    },
    
    saveTheListOfTimeZones : function (data, textStatus, jqXHR) {
        var listOfTimezones = '';
        if(data.timezoneList != null) {
            for(i = 0; i < data.timezoneList.length; i++) {
                TimeZone.addTimeZoneObjectToArray(data.timezoneList[i]);
            }
        }
        
        TimeZone.buildTheToggler();
    },
    
    addTimeZoneObjectToArray : function (timeZone) {
        newTimeZone = new TimeZone.timeZoneObject(timeZone.timezoneCode, timeZone.description, timeZone.timezoneOffset);
        TimeZone.timeZoneList[timeZone.preferenceOptionId] = newTimeZone;
    },
    
    timeZoneObject : function (code, name, offset) {
        this.code = code;
        this.name = name;
        this.offset = offset;
    },
    
    buildTheToggler : function () {
        if(isAuthenticated()) {
            TimeZone.userIsLoggedIn();
        } else {
            TimeZone.userIsNotLoggedIn();
        }
        TimeZone.updateTimeZoneCodeInToggler();
        TimeZone.enableTimeZoneListToggle();
    },
    
    enableTimeZoneListToggle : function () {
        jQuery('#displayedTime').unbind('click').click(function() {
            jQuery("#selectWrapper").toggle();
            jQuery('#timeZoneSelector').tinyscrollbar();
        });
    },
 
    /*
     * GETTER Methods
     */
    getTimeZoneId : function () {
        return TimeZone.currentTimeZone;
    },
    
    getTimeZoneCode : function () {
        return TimeZone.timeZoneList[TimeZone.currentTimeZone].code;
    },
    
    getTimeZoneName : function () {
        return TimeZone.timeZoneList[TimeZone.currentTimeZone].name;
    },
    
    getTimeZoneOffset : function () {
        return TimeZone.timeZoneList[TimeZone.currentTimeZone].offset;
    },
    
    getTimeWithTimeZoneOffset : function (timeInMillisecondsInGMT) {
        return timeInMillisecondsInGMT + (TimeZone.getTimeZoneOffset() * 3600000);
    }
    
};;
var Forms = {
  
    init : function() {
        Forms.setUpFormsToSubmitOnReturn();
    },
    
    setUpFormsToSubmitOnReturn : function() {
        var returnKeyCode = 13;
        
        jQuery('input').keydown(function(data){
            if (data.keyCode == returnKeyCode) {
                jQuery(this).parents('form').submit();
                return false;
            }
        });
    },
    
    isReadyForSubmit : function(formElement) {
        if (Forms.thisFormCannotBeSubmitted(formElement)) {
            return false;
        } else {
            return true;
        }
    },
    
    thisFormCannotBeSubmitted : function(formElement) {
        return Forms.thisFormIsDisabled(formElement) || Forms.thisFormWasSubmittedLessThanASecondAgo(formElement);
    },
    
    thisFormIsDisabled : function(formElement) {
        return formElement.disableSubmission;
    },
    
    thisFormWasSubmittedLessThanASecondAgo : function(formElement) {
        return (Forms.getCurrentTime() - formElement.lastSubmission) < 1000;
    },
    
    disableThisForm : function(formElement) {
        Forms.setTimeOfLastSubmission(formElement);
        Forms.disableFormSubmission(formElement);
    },  
    
    setTimeOfLastSubmission : function(formElement) {
        formElement.lastSubmission = Forms.getCurrentTime();
    },
    
    getCurrentTime : function() {
        return new Date().getTime();
    },
    
    disableFormSubmission : function(formElement) {
        formElement.disableSubmission = true;
    },
    
    reenableFormSubmission : function(formElement) {
        formElement.disableSubmission = false;
    }
    
};;
var ErrorHandling = {

    $errorMessageDiv : '.errorHandlingMessage',

    showErrorMessage : function(elementToFollow, newErrorMessage) {
        var errorMessage;
        
        if(newErrorMessage) {
            errorMessage = newErrorMessage;
        } else {
            errorMessage = ErrorHandling.getTheDefaultErrorMessage();
        }

        ErrorHandling.removeErrorMessage();
        ErrorHandling.addTheErrorMessageDiv(elementToFollow);
        jQuery(ErrorHandling.$errorMessageDiv).html('<p>' + errorMessage + "</p>").show();
    },
    
    getTheDefaultErrorMessage : function() {
        return 'We are unable to complete this transaction at this time. Please try again later or contact our Customer Service department.';
    },
    
    addTheErrorMessageDiv : function(elementToFollow) {
        jQuery('<div class="errorHandlingMessage"></div>').insertAfter(elementToFollow);
    },
    
    removeErrorMessage : function() {
        jQuery(ErrorHandling.$errorMessageDiv).remove();
    }
    
};
;
jQuery(document).ready(function($) {
  
    var HeaderMessage = {

        cookieName : "NewJoin",
        
        $headerMessage : $("#headerMessage"),
        $headerMessageCloseButton : $("#headerMessage .close a"),

        init : function() {
            if(HeaderMessage.weShouldShowTheHeaderMessage()) {
                HeaderMessage.showHeaderMessage();
                HeaderMessage.setupHeaderMessageCloseButton();
            }
        },
        
        weShouldShowTheHeaderMessage : function() {
            return $.cookie(HeaderMessage.cookieName) == 'yes' && isAuthenticated();
        },
        
        showHeaderMessage : function() {
            HeaderMessage.$headerMessage.show();
        },
        
        setupHeaderMessageCloseButton : function() {
            HeaderMessage.$headerMessageCloseButton.click(function() {
                HeaderMessage.fadeOutHeaderMessage();
                HeaderMessage.unsetTheHeaderMessageCookie();
            });
        },
        
        fadeOutHeaderMessage : function() {
            HeaderMessage.$headerMessage.fadeOut(300);
        },
        
        unsetTheHeaderMessageCookie : function() {
            var domainName = HeaderMessage.getCookieDomain();
            $.cookie(HeaderMessage.cookieName, null, { domain : domainName, path : "/" });
        },
        
        getCookieDomain : function() {
            var hostname = window.location.hostname;
            return hostname.replace(hostname.split('.', 1)[0], '');
        }
        
    };

    HeaderMessage.init();
    
});
;

