/**
 * Some common javascript functions.
 * Putting them here makes reuse easier, and allows caching to
 * do it's thing.
 */


/**
 * Catch clicks and close pop-ups.
 */
document.onclick = closeOpenMenus;

/**
 * Attach a "submit on enter" event handler to the given input element.
 */
function attachFormSubmitHandler( input )
{
    input.onkeydown = function( e ) 
    {
        var KEY_ENTER = 13; 
        if ( !e ) e = window.event;
        var code = e.keyCode ? e.keyCode : e.which;
        if ( code == KEY_ENTER )
        {
            // try to call the onsubmit handler first. browsers won't call this
            // automatically if a form is submitted programatically.
            if ( input.form.onsubmit ) input.form.onsubmit();
            input.form.submit();
        }
    }
}

/**
 * Find all form elements on window load and attach a "submit on enter" 
 * event handler to each input element in the form.
 */
function attachFormSubmitHandlers() 
{
    var forms = document.getElementsByTagName( "form" );
    for ( var i = 0; i < forms.length; i++ )
    {
        var inputs = forms[i].getElementsByTagName( "input" );
        for (var j = 0; j < inputs.length; j++ )
            attachFormSubmitHandler( inputs[j] );
    }
}

/**
 * Preload rollover graphics.
 */

var btnSearchOver = new Image();
var btnSignInOver = new Image();
var btnEditOver = new Image();
var btnAddOver = new Image();
var btnHistoryOver = new Image();
var btnDeleteOver = new Image();
var btnFilterOver = new Image();
var btnProfileOver = new Image();
var btnReviewsOver = new Image();
var btnSignOutOver = new Image();
var btnHelpOver = new Image();
var btnSplashOver = new Image();
var bigButtonOver = new Image();
var bigButtonDarkOver = new Image();

function preloadImages()
{

	btnSearchOver.src = imageUrl + 'btnSearchOver.gif';
	btnSignInOver.src = imageUrl + 'btnSignInOver.gif';
	btnEditOver.src = imageUrl + 'btnEditOver.gif';
	btnAddOver.src = imageUrl + 'btnAddOver.gif';
	btnHistoryOver.src = imageUrl + 'btnHistoryOver.gif';
	btnDeleteOver.src = imageUrl + 'btnDeleteOver.gif';
	btnFilterOver.src = imageUrl + 'btnFilterOver.gif';
	btnProfileOver.src = imageUrl + 'btnProfileOver.gif';
	btnReviewsOver.src = imageUrl + 'btnReviewsOver.gif';
	btnSignOutOver.src = imageUrl + 'btnSignOutOver.gif';
	btnHelpOver.src = imageUrl + 'btnHelpOver.gif';
	btnSplashOver.src = imageUrl + 'btnSplashOver.png';
	bigButtonOver.src = imageUrl + 'bigButtonOver.gif';
	bigButtonDarkOver.src = imageUrl + 'bigButtonDarkOver.gif';
	
}

/**
 * Take a path and return the basename.
 */
function getBaseName( path )
{
    var needle = "/";
    if ( !path.match( "/" ) ) needle = "\\";
    return path.substring( path.lastIndexOf( needle ) + 1 );
}


/**
 * Take a path and return the dirname.
 */
function getDirName( path )
{
    var needle = "/";
    if ( !path.match( "/" ) ) needle = "\\";
    return path.substring( 0, path.lastIndexOf( needle ) );
}


/**
 * Check the supplied passwords and ensure that they match.
 */
function checkPasswords()
{

	if ( document.userForm.changePassword.value == false )
		return true;

	passwordOne = document.userForm.elements['user[password]'].value;
	passwordTwo = document.userForm.confirmPassword.value;

	if ( passwordOne == '' ) 
	{
		alert( 'You have not entered a password. The password field is required.' );
		return false;
	}

	if ( passwordOne.length < 5 )
	{
		alert( 'The password you have chosen is too short. Please enter a password at least five characters in length.' );
		return false;
	}

	if ( passwordOne.length > 15 )
	{
		alert( 'The password you have chosen is too long. Please enter a password no more than fifteen characters in length.' );
		return false;
	}

	if ( passwordTwo != '' && passwordOne != passwordTwo )
	{
		alert( 'The passwords you have entered do not match. Please try again.' );
		return false;
	}

	return true;

}

/* Toggles an object's class between "<foo>Open" and "<foo>Closed" */

function toggleSection( id )
{
    element = document.getElementById( id );
    elClass = element.className; 
    elClassLength = elClass.length;

    if (elClass.search(/Closed\b/) > -1)
    {
       element.className = elClass.substr(0, elClassLength - 6) + "Open";
    } else if (elClass.search(/Open\b/) > -1)
    {
       element.className = elClass.substr(0, elClassLength - 4) + "Closed";
    }
}

function openSection( id )
{
	div = document.getElementById( id ); 
    if ( div.className.match( "Closed" ) )
        toggleSection( id );
}


function closeSection( id )
{
	div = document.getElementById( id ); 
    if ( div.className.match( "Open" ) )
        toggleSection( id );
}


var openMenus = new Array();
function togglePopUpMenu( e, object, id, contentWindow )
{

    if ( contentWindow === undefined ) var contentWindow = window;

	// bring the popUp div into scope and stop event bubbling.
	var popUpMenu = contentWindow.document.getElementById( id );
	popUpMenu.onclick = stopBubbling;
	stopBubbling( e );
	
	// disable transparency for Opera.
	if ( getBrowser() == 'Opera' )
		popUpMenu.style.opacity = 1;

	// toggle the div.
	if ( popUpMenu.style.visibility != 'visible' )
	{
		closeOpenMenus( contentWindow.document );
		if ( getWindowWidth( contentWindow ) > 
			( popUpMenu.offsetWidth + getOffsetLeft( object ) ) )
		{
			popUpMenu.style.left = getOffsetLeft( object ) + "px";
		} else {
			popUpMenu.style.left = ( getWindowWidth( contentWindow ) - 
                popUpMenu.offsetWidth - 25 ) + "px";
		}
		popUpMenu.style.top = ( getOffsetTop( object ) + 
            object.offsetHeight ) + "px";
		popUpMenu.style.visibility='visible';
        openMenus[ id ] = true;
	} else {
		popUpMenu.style.visibility='hidden';
		openMenus[ id ] = false;
	}

}


function closeOpenMenus()
{

	for ( var id in openMenus )
	{
		var popUpMenu = document.getElementById( id );
        if ( popUpMenu && popUpMenu.style )
        {
            popUpMenu.style.visibility='hidden';
            openMenus[ id ] = false;
        }
	}

}


function getOffsetLeft( object )
{

	var curleft = 0;
	if ( object.offsetParent )
	{
		while ( object.offsetParent )
		{
			curleft += object.offsetLeft
			object = object.offsetParent;
		}
	}
	else if ( object.x )
		curleft += object.x;
	return curleft;

}


function getOffsetTop( object )
{

	var curtop = 0;
	if ( object.offsetParent )
	{
		while ( object.offsetParent )
		{
			curtop += object.offsetTop
			object = object.offsetParent;
		}
	}
	else if ( object.y )
		curtop += object.y;
	return curtop;

}


function trim( string )
{
	return string.replace(/^\s+|\s+$/g, ""); 
}


function getWindowWidth( contentWindow )
{
    
    if ( contentWindow === undefined ) var contentWindow = window;
    
	if ( typeof( contentWindow.innerWidth ) == 'number' )
	{
		return contentWindow.innerWidth;
	} else if ( contentWindow.document.documentElement && 
		( contentWindow.document.documentElement.clientWidth || 
		contentWindow.document.documentElement.clientHeight ) ) 
	{
		return contentWindow.document.documentElement.clientWidth;
	} else if ( contentWindow.document.body && 
		( contentWindow.document.body.clientWidth || 
        contentWindow.document.body.clientHeight ) ) 
	{
		return contentWindow.document.body.clientWidth;
	}
}


function stopBubbling( e )
{
	if ( !e ) var e = window.event;
	e.cancelBubble = true;
	if ( e.stopPropagation ) e.stopPropagation();	
}

function getBrowser()
{

	// detect Opera.
	if ( window.opera )
		return "Opera";

	// detect Safari.
	if ( navigator.userAgent.indexOf( "Safari" ) != -1 )
		return "Safari";

	// detect Konqueror.
	if ( navigator.userAgent.indexOf( "Konqueror" ) != -1 )
		return "Konqueror";

	// detect IE.
	if ( navigator.userAgent.indexOf( "MSIE" ) != -1 )
		return "IE";

	// detect Gecko (Firefox, Camino, Netscape).
	if ( navigator.userAgent.indexOf( "Gecko" ) != -1 )
		return "Gecko";
		
	// default to generic mozilla.
	return "Mozilla";

}


function isIE()
{
	if ( getBrowser() == 'IE' )
		return true;
	else
		return false;
}


function nl2br( text )
{
	text = escape(text);
	if ( text.indexOf( '%0D%0A' ) > -1 )
	{
		match = /%0D%0A/g;
	}
	else if ( text.indexOf( '%0A' ) > -1 )
	{
		match = /%0A/g;
	}
	else if ( text.indexOf( '%0D' ) > -1 )
	{
		match = /%0D/g;
	}
	return unescape( text.replace( match, '<BR/>' ) );
}


function splitWords( string, length )
{

    // break words with '&shy;' if IE, '&#8203' otherwise.
    if ( getBrowser() == "IE" )
    {
        delimiter = "&shy;";
    } else {
        delimiter = "&#8203;";
    }

    // break words with our delimiter of choice.
    words  = string.split( " " );
    string = "";
    for ( i = 0; i < words.length; i++ )
    {
        parts  = new Array();
        for ( j = 0; j < Math.ceil( words[i].length / length ); j++ )
            parts.push( words[i].substr( j*length, length ) );
        string += parts.join( delimiter );
    }

    return string;

}


function scrunchString( string, length )
{
	s = new String( string );
	if ( ( s.length > length ) && ( length > 4 ) )
	{
		left  = s.substr( 0, Math.ceil( length / 2 ) - 1 );
		right = s.substr( ( Math.floor( length / 2 ) - 1 ) * -1 );
		s = left + ".." + right;
	}
	return s;
}


/**
 * A function to make a RPC (remote procedure call)
 * and return the result.
 */
var rpcCount = 0;
function rpc( request, callback )
{

	var head = document.getElementsByTagName( 'head' ).item( 0 );
	var script = document.createElement( 'script' );
	script.id = 'rpc' + rpcCount;
    var src = baseUrl + request;
    if ( callback !== undefined && callback.length > 0 )
        src += "&callback=" + callback;
    src += "&" + new Date().getTime();
	script.src = src;
    script.type = 'text/javascript';
	script.defer = true;
	rpcCount++;
	head.appendChild( script );

}


/**
 * Select all elements in an input field.
 */
function selectAll( id )
{
	field = document.getElementById( id );
	var toggle = !field.options[ 0 ].selected;
	for ( i = 0; i < field.length; i++ ) 
		field.options[ i ].selected = toggle; 
}


/**
 * Some cookie accessors/mutators.
 */
function setCookie(name, value, path, expires, domain, secure) 
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie(name) 
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(name, path, domain) 
{
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

function toggleBlind(id)
{
	// swap the expand/collapse graphic to reflect the change.
	if ( document.getElementById( id ).style.display == "none" )
	{
		document.images[ id + 'Btn' ].src = imageUrl + 'btnCollapse.gif';
	} else {
		document.images[ id + 'Btn' ].src = imageUrl + 'btnExpand.gif';
	}
	new Effect.toggle(id, 'blind', {duration: 0.3});
}

function togglePerforceUser(isNewUser)
{
	// toggle userName field and set focus
	var currentState = document.userForm.elements['user[userName]'].disabled;
	document.userForm.elements['user[userName]'].disabled = !currentState;
	if ( currentState )
	    document.userForm.elements['user[userName]'].focus();
	
	// if not a new user, we must be promoting or demoting. 
	// disable problematic form elements
	if ( !isNewUser )
	{
		document.userForm.elements['user[email]'].disabled = currentState;
		document.userForm.elements['toggleChangePassword'].disabled = currentState;
	}    		
}


/**
 * Get the inner text of an element.
 */
function getInnerText( element )
{
    if ( element.innerText !== undefined )
        return element.innerText;
    else
        return element.textContent;
}


/**
 * Get the inner text of an element.
 */
function setInnerText( element, text )
{
    if ( element.innerText !== undefined )
        element.innerText = text;
    else
        element.textContent = text;
}


/**** Three functions to assist with default values in a search form ****/

/**
 * Clear a form field's default text when field gets the focus
 */
function formFieldClear( field, text ) 
{
    if (field.value == text) {
        field.value = "";
    }
}

/**
 * Restore an empty form field's default text when empty field loses focus
 */
function formFieldRestore( field, text ) 
{
    if (field.value == "") {
        field.value = text;
    }
}

/**
 * When the submit button is pressed and the default value is 
 *   found in the search field, replace the default value 
 *   with an empty string.
 */
function preSubmitValidation( field, defaultValue ) 
{        
  if (field.value == defaultValue)
  {
    field.value = "";  
  }
}


