var 
console,
$j = jQuery.noConflict(),
translated_text = [],

EMAIL_REGEX = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i,
USERNAME_REGEX = /^[a-zA-Z0-9][a-zA-Z0-9_-]+[a-zA-Z0-9]$/,
SUBDOMAIN_REGEX = /^[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]$/,
US_PHONE_NUMBER_REGEX = /^\d{10}$/,
PHONE_NUMBER_REGEX = /^(\d)+$/,
SCRIPT_TAGS_REGEX = /<script[^>]*>.*?<\/script>/i,
LINK_REGEX = /^(https?:\/\/)?[^<^>]+/,

AJAX_ANALYTICS = 1; // Flag to turn off all analytic tracking made for Ajax requests.

/**
 * Returns the version of Internet Explorer or a -1 (indicating the use of another browser).
 */
function getInternetExplorerVersion()
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

/**
* Makes an AJAX call to the specified url with the received parameters. 
* The returnFunction is executed when a response from the server is received.
* @param string   url            the url used to make a request to the server
* @param jParams  Object         parameters sent to the server
* @param function returnFunction the function that is executed once the server responds
*/
function goAjax( url, jParams, returnFunction ){
    $j.post( url, jParams, returnFunction);
}

/**
* Counts the amount of items of an object or array
* @param mixed object   container of which we are going to count the items of
* @return int amount of items in the container
*/
function count(object)
{
    var count = 0;
    for(var i in object)
    {
        count++;
    }
    return count;
}

function trim(string)
{
    for(i=0; i<string.length; )
    {
        if(string.charAt(i)==" " || string.charAt(i)=="\n" || string.charAt(i)=="\t")
            string=string.substring(i+1, string.length);
        else
            break;
    }

    for(i=string.length-1; i>=0; i=string.length-1)
    {
        if(string.charAt(i)==" " || string.charAt(i)=="\n" || string.charAt(i)=="\t")
            string=string.substring(0,i);
        else
            break;
    }
    return string;
}

/**
 * Default function for the "on blur" event
 * @param object dom_obj Obj executing the event
 * @param string translate_key to be used on the translated_text array
 */
function inputOnBlur(dom_obj, translate_key, color)
{
    var input = $j(dom_obj);
    if( input.val().replace(/ /g, '') == '')
    {
        input.val(translated_text[translate_key]);
        if( typeof(color) != 'undefined' )
        {
            input.css('color', color);
        }
    }
};

/**
* Default function for the "on focus" event
* @param object dom_obj Obj executing the event
* @param string translate_key to be used on the translated_text array
*/
function inputOnFocus(dom_obj, translate_key, color)
{
    var input = $j(dom_obj);
    
    if( input.val() == translated_text[translate_key] )
    {
        input.val('');
        if( typeof(color) != 'undefined' )
        {
            input.css('color', color);
        }
    }
};

/*
 * Function to change the selected links style
 * currentPageLink is a jquery object that references the link to format
 */
function empty(string)
{
    return ( string.replace(/ /g, '') == '' );
}

function isset(array, index)
{
    return typeof(array[index]) != 'undefined';
}


function formatSelectedPage(currentPageLink,pushDown, factor)
{
	if(currentPageLink)
	{
		currentPageLink.css('fontWeight','bold');
		currentPageLink.css( 'text-decoration', 'none' );	
	}
	if(typeof pushDown && pushDown === true)
	{
		currentPageLink.css( 'position', 'relative' );	
		currentPageLink.css( 'top', factor );	
	}
}

/*
 * Validates a string to contain only numeric chars
 * Does not allow '.' because its used for zip fields for example
 */
 function isNumeric(sText)
{
	var ValidChars = "0123456789";
	var IsNumber=true;
	var Char;

	for (i = 0; i < sText.length && IsNumber == true; i++) 
	{ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) 
		{
			IsNumber = false;
		}
	}
	return IsNumber;
}

function defaultImage(img, type){
    if(type == 'avatar'){
        img.src = AVATAR_SERVER + "default-avatars/1.jpg"
    }else if(type == 'avatar-thumb'){
        img.src = AVATAR_SERVER + "default-avatars/1_t.jpg"
    }
}

// GOOGLE ANALYTICS CALL
function gaTrack(_url )
{
    try
    {// pageTracker is defined in /layouts/layout.phtml
        pageTracker._trackPageview(_url );
    }
    catch(er){}
}


/**
 * Creates a cookie
 * @param name of the cookie
 * @param value of the cookie
 * @param days before expiration
 */
function createCookie(name, value, days)
{
    var expires = "";

    //----------------
    // Build the expiration date
    if( typeof(days) == 'undefined' )
    {
        days = 365;
    }
    var date = new Date();
    date.setTime( date.getTime()+(days * 24 * 60 * 60 * 1000) );
    expires = "; expires="+date.toGMTString();

    //alert(name+"="+value+expires+"; path=/");
    document.cookie = name+"="+value+expires+"; path=/";
}

/**
 * Gets the value of the cookie
 * @param name of the cookie
 * @return value of the cookie
 */
function readCookie(name)
{
    var value = null;
    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 value;
}

/**
 * Deletes a cookie
 * @param name of the cookie
 */
function eraseCookie(name)
{
    createCookie(name,"",-1);
}

var replaceProfanities; 


$j(function(){
    // TMP :: DEBUG CODE
    // CHECK FOR/REPLACE CONSOLE SO WE DON'T HAVE TO REM LOG CALLS WHILE TESTING IN OTHER BROWSERS.
    if( !console ){
        console = {};
        console.log = function(){};
    }
    
    
    // ENCAPSULATED PROFANITY LIST
    var _profanities =
    [
        /\sShit\s/ig,
        /Piss/ig,
        /Motherfucker/ig,
        /Fuck/ig,
        /Cunt/ig,
        /Cocksucker/ig,
        /\sTits\s/ig
    ];
    
    replaceProfanities = function( _str, _replace_str )
    {
        _replace_str = _replace_str || '*@#$#^#$^*';
    
        for( var i in _profanities )
            _str = _str.replace( _profanities[i], _replace_str );
            
        return _str;
    }

  // EXTENDED jQuery METHODS
    // ajax()
    jQuery.superAjax = jQuery.ajax;
    jQuery.ajax = function( settings )
    {
        // Run GA page-tracker if the no_ga setting's not present &
        // our ajax-analytics flag is on &
        // the url doesn't have 'is-auto-request=true'
        if( ! settings.no_ga && AJAX_ANALYTICS && 
            settings.url.indexOf('is-auto-request=true')==-1 ) 
            gaTrack( settings.url );         

        return jQuery.superAjax( settings );
    };
       
});

//textEquals() selector: similar to contains(), but finds exact matches
$j.expr[':'].textEquals = function(a, i, m) {
	return $j(a).text().match("^" + m[3] + "$");
};