try {
  document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}

if(!MB) {
	var MB = function() {
		return {
			lang: {},
			constant: {},
			util: {},
			home: {}
		};
	}();
}

MB.lang = function() {
	var dict = {};
	
	return {
		setLanguage: function(data) {
      for(var i in data) {
        dict[i] = data[i];
      }
		},
		
		get: function(key, plural_key, num) {
      if(plural_key) {
        if(num > 1) {
          if(dict[plural_key]) return dict[plural_key].replace(/%1/, num);
          return plural_key.replace(/%1/, num);
        }
        else {
          if(dict[key]) return dict[key].replace(/%1/, num);
          return key.replace(/%1/, num);
        }
      }
      if(dict[key]) return dict[key];
      return key;
    }
	};
}();

var _ = MB.lang.get;


function confirmDelete(msg, url) {
	if(confirm(msg))
		window.location = url;
	else
		return false;
}

function checkAll(formEl, el) {
	if(el.checked) {
		checked = true;
	}
	else {
		checked = false;
	}
	
	for(var i = 0; i < formEl.elements.length; i++) {
		if (formEl.elements[i].type == 'checkbox') {
			formEl.elements[i].checked = checked;
		}
	}
}

MB.util.formatNumber = function(n, c) {
	if(parseFloat(n) == 'NaN') return n;
	var config = c || {};
	if(config.grp_sep === false)
		var num_grp_sep = '';
	else if(config.grp_sep)
		var num_grp_sep = config.grp_sep;
	else
		var num_grp_sep = ',';
	var dec_sep = config.dec_sep || '.';
	var round = (typeof(config.round) == 'undefined') ? 2 : config.round;
	var precision = (typeof(config.precision) == 'undefined') ? 2 : config.precision;

  var n = n.toString();
  if(n.split) n = n.split('.');
  else return n;

  if(n.length > 2) return n.join('.');
	if(round > 0 && n.length > 1) {
	  n[1] = parseFloat('0.' + n[1]);
	  n[1] = Math.round(n[1] * Math.pow(10, round)) / Math.pow(10, round);
	  n[1] = n[1].toString().split('.')[1];
	}
  if(round <= 0) { // round to whole number
    n[0] = Math.round(parseInt(n[0]) * Math.pow(10, round)) / Math.pow(10, round);
    n[1] = '';
  }

  if(precision >= 0) {
    if(n.length > 1 && typeof n[1] != 'undefined') n[1] = n[1].substring(0, precision);
		else n[1] = '';
    if(n[1].length < precision) {
      for(var wp = n[1].length; wp < precision; wp++) n[1] += '0';
    }
  }

	if(num_grp_sep != '') {
	  var regex = /(\d+)(\d{3})/;
	  while(regex.test(n[0])) n[0] = n[0].toString().replace(regex, '$1' + num_grp_sep + '$2');
	}
  return n[0] + (n.length > 1 && n[1] != '' ? dec_sep + n[1] : '');
}

MB.format = MB.util.formatNumber;

MB.util.stats = {}
MB.util.stats.pageType = null;
MB.util.stats.siteIds = null;
MB.util.stats.callInProgress = false;
MB.util.stats.currentChartUrl = null;
MB.util.stats.currentRow = null;
MB.util.stats.over = function(e, a) {
	p = a.parentNode;
	while(p.tagName.toLowerCase() != 'tr') {
		p = p.parentNode;
	}
	p.className = 'hover';
}

MB.util.stats.out = function(e, a) {
	p = a.parentNode;
	while(p.tagName.toLowerCase() != 'tr') {
		p = p.parentNode;
	}
	p.className = '';
}

MB.util.stats.init = function() {
	// get all tr children of the stats table and attach events
	var tableRows = Ext.DomQuery.select('tr', Ext.get('statsTable').dom);

	for(var i in tableRows) {
		if(typeof tableRows[i].tagName != 'undefined' && tableRows[i].id != MB.util.stats.currentRow && tableRows[i].tagName.toLowerCase() == 'tr') {
			Ext.get(tableRows[i]).on('mouseover', MB.util.stats.over);
			Ext.get(tableRows[i]).on('mouseout', MB.util.stats.out);
		}
	}
	window.setTimeout('MB.util.stats.liveUpdate()', 5000);
}

MB.util.stats.liveUpdate = function() {
	var numbers = Ext.DomQuery.select('td[class=number]', Ext.get('statsTable').dom);
	var url = MB.constant.base_control + 'ajax/live_stats/';
	var postData = 'type=' + MB.util.stats.pageType + '&ids=' + encodeURI(MB.util.stats.ids);
	var success = function(data, ops) {
		var stats = Ext.util.JSON.decode(data.responseText);
		if(stats == 0) window.location = MB.constant.base_control + 'home/login/?access'; 
		for(var i in stats) {
			if(Ext.get(i)) {
				var el = Ext.DomQuery.selectNode('span[class=largeGreenTextBold]', Ext.get(i).dom);
				if(el.innerHTML != stats[i]) {
					Ext.get(el).highlight();
					el.innerHTML = stats[i];
				}
			}
		}
		window.setTimeout('MB.util.stats.liveUpdate()', 14000);
	}
	var cObj =	Ext.Ajax.request({success: success, params: postData, url: url});
}

MB.util.stats.getChart = function(chartType, url, postData, target, row) {
	if(MB.util.stats.currentChartUrl == postData || MB.util.stats.callInProgress) return;
	MB.util.stats.callInProgress = true;

	Ext.get('chartSpinner').show();
	var chartUrl = '';
	switch(chartType) {
		case 'column':
			chartUrl = MB.constant.base_url + 'Charts/FC_3/StackedColumn2D.swf';
			break;
		case 'notstacked':
			chartUrl = MB.constant.base_url + 'Charts/FC_3/Column2D.swf';
			break;
	}

	var success = function(data) {
	  if(data.responseText == 0) window.location = MB.constant.base_control + 'home/login/?access'; 
		Ext.get('chartSpinner').hide();
		if(typeof MB.util.stats.currentRow != 'undefined') {
			Ext.get(MB.util.stats.currentRow).on('mouseover', MB.util.stats.over);
			Ext.get(MB.util.stats.currentRow).on('mouseout', MB.util.stats.out);
			Ext.get(MB.util.stats.currentRow).dom.className = '';
		}

	    var myChart = new FusionCharts(chartUrl, "title", "555", "300", "0", "0");
	    myChart.setDataXML(data.responseText);
	    myChart.render(target);
	    MB.util.stats.currentChartUrl = postData;
	    // save state of row
	    MB.util.stats.currentRow = row.id;
        Ext.get(row.id).removeListener('mouseover', MB.util.stats.over);
    	Ext.get(row.id).removeListener('mouseout', MB.util.stats.out);
    
	    row.className = 'active';
	    
    	MB.util.stats.callInProgress = false;
	}
	
	var cObj =	Ext.Ajax.request({success: success, params: postData, url: url});

}

var helpTipDialog;
var htClick = function(e) {
	if(!e.within(helpTipDialog.el.dom))
		helpTipDialog.hide();
}

var helpTip = function(id, content, w) {
	w = w || 300;
	
	if(!helpTipDialog){ // lazy initialize the dialog and only create it once
		Ext.get(document.body).insertHtml('beforeEnd', '<div id="help-tip" style="visibility:hidden;position:absolute;top:0px;"><div class="x-dlg-hd">Help</div><div class="x-dlg-bd"></div></div><div id="help-tip-helper" style="visibility:hidden;position:absolute;top:0px;"></div>');
  	helpTipDialog = new Ext.BasicDialog('help-tip', {
        				resizable:false,
        				draggable:false,
        				autoTabs:false,
        				title:_('Help'),
        				collapsible:false,
                shadow:false
        });
  	Ext.get('help-tip-helper').setOpacity(0).show();
  	helpTipDialog.body.set({overflow: 'hidden'});
    helpTipDialog.addKeyListener(27, helpTipDialog.hide, helpTipDialog);
    helpTipDialog.on('beforeHide', function() { Ext.get(document).un('click', htClick); });
  } else {
  	helpTipDialog.hide();
  }
	Ext.get('help-tip-helper').setWidth(w).dom.innerHTML = content;
  helpTipDialog.setContentSize(w, Ext.get('help-tip-helper').getHeight() + 13);
  Ext.get('help-tip-helper').hide();
  helpTipDialog.body.update(content);
  helpTipDialog.anchorTo(id, 'bl');
  helpTipDialog.show();
  window.setTimeout( function() { 
  	Ext.get(document).on('click', htClick );
  }, 500);
}

// infamous http://www.quirksmode.org/js/cookies.html cookie code
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

MB.onReadyStack = [];
MB.onReady = function(f, s, o) {
	MB.onReadyStack.push([f,s,o]);
}

MB.home.gaugeMax = 3500;
MB.home.gaugeValue = MB.home.gaugeMax / 2;
MB.home.lastReqs = [];
MB.home.updateReturned = true;

MB.home.runadcounter = function() {
	Ext.Ajax.request({
		url: MB.constant.base_control + "ajax/get_ads_viewed/",
		success: function(response, ops) {
			var data = response.responseText;
			if (('' != data) && (!isNaN(parseInt(data))) && Ext.get('adViewsData')) {
				Ext.get('adViewsData').dom.innerHTML = data;
			}
		}
	});
  window.setTimeout(MB.home.runadcounter, 3000);
}

MB.home.gaugeloop = function() {
		if(MB.home.updateReturned) {
			Ext.Ajax.request({
				url: MB.constant.base_control + 'ajax/get_live_request/?f=json',
				success: function(response, ops) {
					var click = Ext.decode(response.responseText);
					MB.home.lastReqs.push(click['reqs']);
					if(MB.home.lastReqs.length > 3) MB.home.lastReqs.shift();
					MB.home.gaugeValue = 0;
					for(var i = 0; i < MB.home.lastReqs.length; i++) {
						MB.home.gaugeValue += MB.home.lastReqs[i];
					}
					MB.home.gaugeValue = Math.min(MB.home.gaugeValue / MB.home.lastReqs.length, MB.home.gaugeMax);
				  if(getChartFromId('gauge') && getChartFromId('gauge').feedData) getChartFromId('gauge').feedData('&value=' + MB.home.gaugeValue);
				  MB.home.updateReturned = true;
				}
			});
		}
		MB.home.updateReturned = false;
		window.setTimeout(MB.home.gaugeloop, 2000);
}

MB.PopUp = function() {
	var popup = null;
	var popupContent = null;

	var hideDocumentClick = function(e, el) {
		if(!e.within(popup)) {
			MB.PopUp.hidePopUp();
		}
	}
	
  return {
  	init: function() {
  	  if(popup == null) {
        Ext.get(document.body).insertHtml('beforeEnd', 
        	"<div id='popup' style='visibility:hidden;position:absolute;top:0px;' " +
        	" class='popUpTop'><div class='popUpBottom'><span id='popup-title' style='padding-left: 4px; float: left' class='titleRed'></span><img style='float: right;' id='popup-close' src='" + MB.constant.base_url + 
        	"img/small_close.gif'><div style='clear: both; padding: 4px;' id='popup-body'></div></div></div>");
        popup = Ext.get('popup');
        popupContent = {};
        Ext.get('popup-close').on('click', MB.PopUp.hidePopUp, this);
      }
  	},
    create: function(el, content, title) {
			this.init();
			var id = Ext.get(el).id;
			if(!popupContent[id]) {
				popupContent[id] = {content: content, title: title || ''};
			}
      Ext.get(el).on('click', MB.PopUp.showPopUp, this);
    },
    createFromClick: function(el, content, title) {
    	this.init();
			var id = Ext.get(el).id;
			if(!popupContent[id]) {
				popupContent[id] = {content: content, title: title || ''};
			}
    	MB.PopUp.showPopUp(null, el);
    },
    showPopUp: function(e, el) {
			var id = Ext.get(el).id;
      Ext.get('popup-body').update(popupContent[el.id].content);
      Ext.get('popup-title').update(popupContent[el.id].title);
      popup.anchorTo(el, 'b', [-157 - Ext.get(el).getWidth() / 2, -2]);
      popup.show();
      Ext.get(document.body).on('mousedown', hideDocumentClick);
    },  
    hidePopUp: function() {        
      popup.hide();                
      Ext.get(document.body).un('mousedown', hideDocumentClick);
    }
  };
}();

Array.max = function(a) {
	return Math.max.apply(Math, a);
};
Array.min = function(a) {
	return Math.min.apply(Math, a);
};

MB.TextInputLabeler = function(inputLabel, textInputId) 
{
  var inputLabel = inputLabel;
  var textInput = Ext.get(textInputId);
  var labelClass = 'labelInput';
  var inputClass = 'userInput';

  this.handleBlur = function() {
    if (textInput.dom.value == "" || textInput.dom.value == inputLabel) {
      textInput.removeClass(inputClass);
      textInput.addClass(labelClass);
      textInput.dom.value = inputLabel;
    }
  };

  this.handleFocus = function() {
    if (textInput.dom.value == inputLabel) {
      textInput.dom.value = "";
      textInput.removeClass(labelClass);
      textInput.addClass(inputClass);
    }
  };

  textInput.getValue = function() {
    return (textInput.dom.value == inputLabel) ? "" : textInput.dom.value;
  };

  textInput.on('blur', this.handleBlur);
  textInput.on('focus', this.handleFocus);

  textInput.blur();
  this.handleBlur();
  textInput.dom.readOnly = false;  
};

