Enjin_Core = { };

///Enjin_Core.MAX_ZINDEX = 2147483580;
Enjin_Core.MAX_ZINDEX = 19999;
Enjin_Core._popup_separator = null;
Enjin_Core.floor = function(value, decimals) {
	var base = Math.pow(10, decimals)*1.0; 
	value *= base;
	value = Math.floor(value);
	value /= base;
	
	return value;
}

Enjin_Core.checkMaxChars = function(element, max_length) {
	var length = $(element).val().length;
	
	if (length >= max_length) {
		var trimmed = $(element).val().substr(0, max_length);
		$(element).val(trimmed);
		return false;
	}
	
	return true;
}

/* from phpjs */
Enjin_Core.__html_translation_table = null;
Enjin_Core.prepare_html_translation_table = function(table, quote_style) {
	if (Enjin_Core.__html_translation_table)
		return; //avoid memory usage
	
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco
    // +   bugfixed by: madipta
    // +   improved by: KELAN
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Frank Forte
    // +   bugfixed by: T.Wild
    // +      input by: Ratheous
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js, meaning the constants are not
    // %          note: real constants, but strings instead. Integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, hash_map = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';

    useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';

    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');
        // return false;
    }

    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    }

    entities['60'] = '&lt;';
    entities['62'] = '&gt;';    


    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
    
    hash_map["'"] = '&#039;';
    Enjin_Core.__html_translation_table =  hash_map;
}

//fast and "enough version"
Enjin_Core.htmlentities = function(string, quote_style) {	
	return string
			.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;')
			.replace(/'/g, '&#039;');
			
}
/* from phpjs */
/*
Enjin_Core.htmlentities = function(string, quote_style) {
    var hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    Enjin_Core.prepare_html_translation_table();
    hash_map = Enjin_Core.__html_translation_table;
    
    //if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
    //    return false;
    //}
    if (quote_style !== 'ENT_NOQUOTES') {
    	hash_map['34'] = '&quot;';
    }
    if (quote_style === 'ENT_QUOTES') {
    	hash_map['39'] = '&#39;';
    }    
    
    
    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.replace(new RegExp(symbol, 'gi'), entity);
    }
    
    return tmp_str;
}*/

/* from phpjs */
Enjin_Core.html_entity_decode = function(str) {
	var chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
	var random_separator;
	var code;
	var cp;
	
	do {
		code = '';
		for (i=0; i<5; i++) {
			cp = parseInt(Math.random() * chars.length);
			code += chars.substr(cp, 1);
		}
		
		random_separator = '@'+code+'@';
	} while (str.indexOf(random_separator) != -1);
	
	
	  var ta=document.createElement("textarea");
	  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(new RegExp("\n", 'g'), random_separator);	  
	  return ta.value.replace(new RegExp(random_separator, 'g'), "\n");
}

Enjin_Core.alert = function(title) {
	Enjin_Core.showMessagePopup({
		message: title,
		button_continue: 'Ok',
		scope: this,
		callback: function() {}, /* doing nothing on call since will be the swf upload part */
		cancel_click_document: true
	});
}

Enjin_Core._popup = null;
Enjin_Core.showMessagePopup = function(options) {
	var middle = 0;
	var _options = {
		top: null,
		message: '',
		button_continue: 'Ok'
	};
	jQuery.extend(_options, options);
	
	if (Enjin_Core._popup)
		Enjin_Core.cancelPopup();
	
	var html = '<div class="delete-comment element_popup hidden">\
		<div class="inner inner-message">\
			<span class="message">'+_options.message+'</span><br><br>\
			<div class="element_button"><div class="l"><!-- --></div><div class="r"><!-- --></div><input type="button" value="'+_options.button_continue+'" class="btncontinue"></div>\
		</div>\
	</div>';
	
	Enjin_Core._popup = $(html);
		
	Enjin_Core._popup.appendTo($(document.body));
	
	Enjin_Core.createPopupSeparator();
	Enjin_Core.placeAfterPopupSeparator(Enjin_Core._popup);
	
	
	//position	
	if (_options.top == null) {
		_options.top = $(window).scrollTop() + 
						($(window).height() - Enjin_Core._popup.height())*0.5;
	}	
	Enjin_Core._popup.css('top', _options.top);
	
	middle = ($(document.body).width() - Enjin_Core._popup.width())*0.5;	
	Enjin_Core._popup.css('left', middle);
	Enjin_Core._popup.show();
	
	Enjin_Core._popup.find('input[type=button].btncontinue').click(function(){
		Enjin_Core.cancelPopup();
	});
}

Enjin_Core.centerPopup = function(popup, top, use_scrolltop) {
	if (typeof use_scrolltop == 'undefined')
		use_scrolltop = true;
	
	var window_top = 0;
	if (use_scrolltop)
		window_top = $(window).scrollTop();
	
	if (top == null) {
		//console.log("T: "+$(window).height()+" -- "+popup.height());
		top = window_top + ($(window).height() - popup.height())*0.5;
	} else {
		top = window_top + top;
	}
	popup.css('top', top);
	
	middle = ($(document.body).width() - popup.width())*0.5;	
	popup.css('left', middle);	
}

Enjin_Core.showPopup = function(options) {
	var middle = 0;
	var html_title = ''; 
	var _options = {
		top: null,
		message: '',
		message1: '',
		button_continue: 'Ok',
		scope: this,
		params: [],
		callback: function() {},
		callback_cancel: function() {},
		cancel_click_document: true
	};
	jQuery.extend(_options, options);
	
	if (Enjin_Core._popup)
		Enjin_Core.cancelPopup();
	
	var html = '<div class="delete-comment element_popup hidden">\
		<div class="inner">\
			<span class="message">'+_options.message+'</span><br><br>\
			|@extra@|\
			<div class="element_button"><div class="l"><!-- --></div><div class="r"><!-- --></div><input type="button" value="'+_options.button_continue+'" class="btncontinue"></div>&nbsp; or &nbsp;<a href="javascript:void(0);" class="cancel" onclick="Enjin_Core.cancelPopup(true)">Cancel</a>\
		</div>\
	</div>';
		
	if (_options.message1 != "") {
		html_title = '<span class="message1">'+_options.message1+'</span><br><br>';
	}
		
	html = html.replace('|@extra@|', html_title);
	
	//prepare base
	Enjin_Core._popup_separator = Enjin_Core.createPopupSeparator();
	
	Enjin_Core._popup = $(html); 
	Enjin_Core._popup.appendTo($(document.body));
	
	//position
	//position	
	if (_options.top == null) {
		_options.top = $(window).scrollTop() + 
						($(window).height() - Enjin_Core._popup.height())*0.5;
	}	
	Enjin_Core._popup.css('top', _options.top);
	
	
	middle = ($(document.body).width() - Enjin_Core._popup.width())*0.5;	
	Enjin_Core._popup.css('left', middle);
	Enjin_Core._popup.show();
	Enjin_Core._popup._options = _options;
	Enjin_Core.placeAfterPopupSeparator(Enjin_Core._popup);
	
	Enjin_Core._popup.find('input[type=button].btncontinue').click(function(){		
		_options.callback.apply(_options.scope, _options.params);
		Enjin_Core.cancelPopup();
	});
	
	if (_options.cancel_click_document) {
		$(document).one("click", function(event) {
			Enjin_Core.cancelPopup(true);
		});
	}
	
	return Enjin_Core._popup;
}

Enjin_Core.createPopupSeparator = function() {
	if (Enjin_Core._popup_separator) {
		return Enjin_Core._popup_separator; //already created
	}
	
	var separator = $('<div class="s_popup-canvas-separator">&nbsp;</div>')
				.css('width', $(document).width())
				.css('height', $(document).height())
				.appendTo(document.body);
	
	$(window).bind('resize', function() {
		separator.css('width', $(document).width());
		separator.css('height', $(document).height());		
	});
	
	Enjin_Core._popup_separator = separator;	
	return separator;
}

Enjin_Core.placeAfterPopupSeparator = function(el) {
	el = $(el);
	el.css('zIndex', Enjin_Core.MAX_ZINDEX+1);
	el.appendTo($(document.body));
}

Enjin_Core.removePopupSeparator = function() {
	if (Enjin_Core._popup_separator) {
		Enjin_Core._popup_separator.remove();
		Enjin_Core._popup_separator = null;
	}
}

Enjin_Core.cancelPopup = function(callback) {		
	if (callback && Enjin_Core._popup) {
		Enjin_Core._popup._options.callback_cancel.apply(
				Enjin_Core._popup._options.scope, 
				Enjin_Core._popup._options.params);		
	}
	
	if (Enjin_Core._popup) {
		Enjin_Core._popup.remove();
		Enjin_Core._popup = null;
	}
	
	Enjin_Core.removePopupSeparator();
}

Enjin_Core.limitText = function(limitField, limitNum) {
	if ($(limitField).val().length > limitNum) {
		$(limitField).val($(limitField).val().substring(0, limitNum));
	}
}

Enjin_Core.buttonState = function(button, state)
{
	if(state == false)
	{
		button.attr('disabled', 'disabled');
		button.parent().addClass('disabled');
	}
	else
	{
		button.removeAttr('disabled');
		button.parent().removeClass('disabled');
	}
}


Enjin_Core._anchorState = {};
Enjin_Core.prepareState = function() {
	var curl = document.location.toString();
	if (curl.match('#')) { // the URL contains an anchor
	  var anchors = curl.split('#');
	  anchors.shift();
	  
	  jQuery.each(anchors, function() {
		  if (this == '#')
			  return; //nothing to do
		  
		  var info = this.split('_');
		  var i=1;
		  var iid = info[1];
		  Enjin_Core._anchorState[iid] = {
				  params: {},
				  anchor: this
		  };
		  
		  
		  for (i=1; i<info.length; i++) {
			  var name = info[i];
			  var value = null; 
			  
			  if (i+1 < info.length)
				  value = info[i+1];
			  
			  Enjin_Core._anchorState[iid][name] = value;
		  }
		  
		  //simulate clicks on anchor		  
		  $('a[href="#' + this + '"]').click();
	  });
	}	
}
Enjin_Core.getState = function(module) {
	if ( Enjin_Core._anchorState[module] ) {
		return Enjin_Core._anchorState[module];
	}
	
	return null;
}

Enjin_Core.disableButton = function(input, seconds, disabledText) {
	if(disabledText != undefined) {
		var origText = $(input).val();
		$(input).val(disabledText);
	}
	
	function reenableButton()
	{
		$(input).removeAttr('disabled');
		$(input).parent().removeClass('disabled');
		if(disabledText != undefined) $(input).val(origText);
	}
	
	$(input).attr('disabled', true);
	$(input).parent().addClass('disabled');
	setTimeout(reenableButton, seconds*1000);
}

/*
 * Dropdown Menu
 */
Enjin_Core.dd_timeout = 500;
Enjin_Core.dd_closetimer = 0;
Enjin_Core.dropdownMenu = function(items, button) {
	Enjin_Core.dd_canceltimer()
	$('.element_dropdown_menu').remove();
	
	var html = '<div class="element_popup element_dropdown_menu">\
		<div class="inner">\
			<ul>';
	
	for(i in items) {
		if(items[i][0] != undefined)
		{
			var target = '';
			if(items[i][2] == 1) target = ' target="_blank"'; 
			html += '<li><a href=\"' + items[i][1] + '\"' + target + '>' + items[i][0] + '</a></li>';
		}
	}
	
	html += '</ul>\
		</div>\
	</div>';
	
	var popup = $(html);
	popup.css({'top': $(button).offset().top + $(button).height(), 'left': $(button).offset().left});
	popup.bind('mouseleave', function(e){
		Enjin_Core.dd_timer();
	});
	popup.bind('mouseenter', Enjin_Core.dd_canceltimer);
	
	$(button).unbind('mouseleave');
	$(button).bind('mouseleave', function(e){
		if(!(e.pageX > $(button).offset().left
		&& e.pageX < $(button).offset().left + $(button).width()
		&& e.pageY > $(button).offset().top)) Enjin_Core.dd_timer();
	});
	
	$('body').prepend(popup);
}
Enjin_Core.dd_close = function() {
	$('.element_dropdown_menu').remove();
}

Enjin_Core.dd_timer = function() {
	Enjin_Core.dd_closetimer = window.setTimeout(Enjin_Core.dd_close, Enjin_Core.dd_timeout);
}
Enjin_Core.dd_canceltimer = function() {
	if(Enjin_Core.dd_closetimer) {
		window.clearTimeout(Enjin_Core.dd_closetimer);
		Enjin_Core.dd_closetimer = null;
	}
}

/* Trial Plan */
Enjin_Core.startTrial = function() {
	$.post("/ajax.php?s=signup", { cmd: 'start-trial' },
		function(data){
			document.location = location.href;
		}
	);
}
Enjin_Core.declineTrial = function() {
	$.post("/ajax.php?s=signup", { cmd: 'decline-trial' },
		function(data){
			$('.trial_popup').fadeOut(400);
		}
	);
}
Enjin_Core.closeTrialReminder = function() {
	$.post("/ajax.php?s=signup", { cmd: 'close-trial-reminder' },
		function(data){
			$('.trial_popup').fadeOut(400);
		}
	);
}

Enjin_Core.stopBubble = function(event) {
	if ($.browser.msie)
		window.event.cancelBubble = true;
	else
		event.stopPropagation();	
}

Enjin_Core.popupWindow = function(url, w, h) {
	var winl = (screen.width-w)/2;
	var wint = (screen.height-h)/2;
	mywindow = window.open(url, "cms_popup","location=0,toolbar=0,status=1,scrollbars=1,width=" + w + ",height=" + h + ",top=" + wint + ",left=" + winl);
}

Enjin_Core.liveSupport = function() {
	$('#livesupport').click(function(){
		if($(this).children('a').text() == 'Live Help') {
			window.location = 'http://www.enjin.com/support/form';
			return false;
		}
	});
}