
// will be overriden by prototype's impl
function $(element)
{
    return document.getElementById( element );
}

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

/**
 * @deprecated due to collision in fsmenu
 */
function isIE()
{
    return isInternetExplorer();
}

function isInternetExplorer()
{
    var userAgent = navigator.userAgent.toLowerCase();
    return ( userAgent.indexOf( "msie" ) != -1 );
}

function isMozilla()
{
    var userAgent = navigator.userAgent.toLowerCase();
    return ( !isInternetExplorer() &&
             userAgent.indexOf( "mozilla" ) != -1 && 
             userAgent.indexOf( "rv:" ) != -1 );
}

function showElement( id )
{
    document.getElementById( id ).style.display = "block";
}

function hideElement( id )
{
    document.getElementById( id ).style.display = "none";
}

function getTop( element, recurse )
{
    var value = 0;
    if ( element != null )
    {
        if ( recurse && element.offsetParent != null )
        {
            value += getTop( element.offsetParent, recurse, true );
        }
        value += element.offsetTop;
    }
    return value;
}

function getLeft( element, recurse )
{
    var value = 0;
    if ( element != null )
    {
        if ( recurse && element.offsetParent != null )
        {
            value += getLeft( element.offsetParent, recurse, true );
        }
        value += element.offsetLeft;
    }
    return value;
}

function getWidth( element )
{
    return element.offsetWidth;
}

function getHeight( element )
{
    //return element.offsetHeight;
    return element.scrollHeight;
}

function findStyleSheetRule( className, styleName )
{
    try
    {
        className = className.toLowerCase();
        for ( var i = 0; i < document.styleSheets.length; i++ )
        {
            var stylesheet = document.styleSheets[i];
            var rules = isInternetExplorer() ? stylesheet.rules : stylesheet.cssRules;
            for ( var j = 0; j < rules.length; j++ )
            {
                var rule = rules[j];
                if ( rule.selectorText.toLowerCase() == className )
                {
                    alert( eval( "rule.style." + styleName ) );
                    return eval( "rule.style." + styleName );
                }
            }
        }
    }
    catch ( e )
    {
        alert( "findStyleSheetRule: " + e.message );
    }
    alert( "returning null" );
    return null;
}

function doSubmit( form )
{
    if ( form != null )
    {
        for ( var i = 0; i < form.elements.length; i++ )
        {
            if ( form.elements[i].type == "submit" )
            {
                //form.elements[i].value = "Please Wait ...";
                form.elements[i].disabled = true;
            }
        }
        form.submit();
    }
    return true;
}

function findParentNodeOfType( childNode, tagName )
{
    if ( childNode != null )
    {
        if ( childNode.tagName != null &&
             childNode.tagName == tagName )
        {
            return childNode;
        }
        else
        {
            return findParentNodeOfType( childNode.parentNode, tagName );
        }
    }
    return null;
}

function findChildNodeOfType( parentNode, tagName )
{
    var childNode = null;
    if ( parentNode != null )
    {
        if ( parentNode.tagName != null &&
             parentNode.tagName == tagName )
        {
            childNode = parentNode;
        }
        else
        {
            var i;
            for ( i = 0; i < parentNode.childNodes.length; i++ )
            {
                childNode = findChildNodeOfType( parentNode.childNodes[i], tagName );
                if ( childNode != null )
                {
                    break;
                }
            }
        }
    }
    return childNode;
}

function toggleRowSelection( element )
{
    var row = findParentNodeOfType( element, "TR" );
    if ( element.checked )
    {
        row.__className = row.className;
        row.className='selectedRow selected';
    }
    else
    {
        row.className = row.__className;
        //row.className='row';
    }
}

function toggleAllRowsSelection( element )
{

    //var className = null;
    //if ( element.checked )
    //{
    //    className='selectedRow selected';
    //}
    //else
    //{
    //    className='row';
    //}
    var table = findParentNodeOfType( element, "TABLE" );
    var i;
    for ( i = 0; i < table.rows.length; i++)
    {
        var row = table.rows[i];
        var visible = ( row.style.display != "none" );
        if ( visible &&
             ( row.className == null ||
               ( row.className.toLowerCase().indexOf( "header" ) == -1 &&
                 row.className.toLowerCase().indexOf( "footer" ) == -1 ) ) )
        {
            //row.className=className;
            var alreadyChecked = false;
            var input = findChildNodeOfType( row, "INPUT" );
            if ( input.id == null || input.id != element.id )
            {
                alreadyChecked = input.checked;
                input.checked = element.checked;
            }
            if ( element.checked )
            {
                if ( !alreadyChecked )
                {
                    row.__className = row.className;
                    row.className='selectedRow selected';
                }
            }
            else
            {
                row.className = row.__className;
                //row.className='row';
            }
        }
    }
}

function initRowSelection()
{
    var tables = document.getElementsByTagName( "TABLE" );
    for ( var i = 0; i < tables.length; i++ )
    {
        var table = tables[i];
        for ( var j = 0; j < table.rows.length; j++)
        {
            var row = table.rows[j];
            if ( row.className == null ||
                 ( row.className.toLowerCase().indexOf( "header" ) == -1 &&
                   row.className.toLowerCase().indexOf( "footer" ) == -1 ) )
            {
                var input = findChildNodeOfType( row, "INPUT" );
                toggleRowSelection( input );
            }
            else if ( row.className != null &&
                      row.className.toLowerCase().indexOf( "header" ) != -1 )
            {
                var input = findChildNodeOfType( row, "INPUT" );
                if ( input != null && input.checked )
                {
                    // this will only affect IE since it is inconsistent and will leave
                    // selectAll checkbox checked b/c uniquely named but not individual
                    // rows/items because they share the same parameter name
                    input.checked = false;
                    toggleAllRowsSelection( input );
                }
            }
        }
    }
}

function countSelectedRows( element )
{
    var count = 0;
    var table = null;
    if ( element.tagName != null && element.tagName == "TABLE" )
    {
        table = element;
    }
    else
    {
        table = findParentNodeOfType( element, "TABLE" );
    }
    for ( var i = 0; i < table.rows.length; i++)
    {
        var row = table.rows[i];
        if ( row.className == null ||
             ( row.className.toLowerCase().indexOf( "header" ) == -1 &&
               row.className.toLowerCase().indexOf( "footer" ) == -1 ) )
        {
            var input = findChildNodeOfType( row, "INPUT" );
            if ( input != null && input.checked )
            {
                count++;
            }
        }
    }
    return count;
}

/**
 * Example: addEvent( document, 'click', new Function("","alert(\'Hello, world!\');return true;"), false );
 */
function addEvent( element, eventType, handler, useCapture )
{
    if ( element.addEventListener )
    {
        element.addEventListener( eventType, handler, useCapture );
        return true;
    }
    else if ( element.attachEvent )
    {
        var result = element.attachEvent( "on"+eventType, handler );
        return result;
    }
    else
    {
        alert( "Handler could not be added" );
        return null;
    }
} 

function removeEvent( element, eventType, handler, useCapture )
{
    if ( element.addEventListener )
    {
        element.removeEventListener( eventType, handler, useCapture );
        return true;
    }
    else if ( element.attachEvent )
    {
        var result = element.detachEvent( "on"+eventType, handler );
        return result;
    }
    else
    {
        alert( "Handler could not be removed" );
        return null;
    }
} 


var modalPopupFeatures = isInternetExplorer() ? "dialogWidth:##WIDTH##px;dialogHeight:##HEIGHT##px;center:yes;resizable:yes" : "resizable=yes,scrollbars=yes,width=##WIDTH##,height=##HEIGHT##,top=##TOP##,left=##LEFT##,dependent=yes,modal=yes,dialog=yes";
var modlessPopupFeatures = isInternetExplorer() ? "resizable=yes,scrollbars=yes,width=##WIDTH##,height=##HEIGHT##,top=##TOP##,left=##LEFT##" : "resizable=yes,scrollbars=yes,width=##WIDTH##,height=##HEIGHT##,top=##TOP##,left=##LEFT##";
var widthPattern = /##WIDTH##/gi;
var heightPattern = /##HEIGHT##/gi;
var leftPattern = /##LEFT##/gi;
var topPattern = /##TOP##/gi;

var locatorPopup = null;
function openLocatorPopup( url, fieldId, width, height, modal )
{
    // determine center position
    var winLeft = 100;
    var winTop = 100;
    if ( !modal || !isInternetExplorer() )
    {
        var w = width + 32;
        var h = height + 96;
        var winLeft = (screen.width - w) / 2;
        var winTop = (screen.height - h) / 2;
        //locatorPopup.moveTo( winLeft, winTop );
        //locatorPopup.focus();
    }

    var features = ( modal ? modalPopupFeatures : modlessPopupFeatures ).replace( widthPattern, width ).replace( heightPattern, height ).replace( leftPattern, winLeft ).replace( topPattern, winTop );

    if ( fieldId != null )
    {
        var field = document.getElementById( fieldId );
        url = appendParameter( url, field.name, field.value );
    }
    if ( isInternetExplorer() && modal )
    {
        var retVal = window.showModalDialog( url, null, features );
        if ( retVal != null && retVal.length == 2 )
        {
            updateField( fieldId, retVal[0], retVal[1] );
        }
    }
    else
    {
        locatorPopup = window.open( url, 'locatorPopup', features );
        locatorPopup.fieldId = fieldId;
        locatorPopup.onunload = updateFieldAsynchronously;
    }
    return false;
}

function appendParameter( url, name, value )
{
    var newUrl = new String( url );
    if ( newUrl.indexOf( "?" ) == -1 )
    {
        newUrl += "?";
    }
    else if ( newUrl.indexOf( "&" ) != newUrl.length-1 )
    {
        newUrl += "&";
    }
    newUrl += ( name + "=" + ( value != null ? value : "" ) );
    return newUrl;
}

function getQueryString()
{
    return window.location.search.substring(1);
}

function parseQueryString( queryString )
{
    var values = [];

    if ( !queryString )
    {
        queryString = getQueryString();
    }

    if ( queryString != null && queryString.length > 0 )
    {
        var pairs = queryString.split( "&" );
    
        for ( var i = 0; i < pairs.length; i++ )
        {
            var pair = pairs[i];
            if ( pair != null && pair.length > 0 )
            {
                var nameValue = pair.split( "=" );
                if ( nameValue.length == 1 )
                {
                    nameValue.push( "" );
                }
                else
                {
                    nameValue[1] = unescape( nameValue[1] ).replace(/\+/g,' ');
                }
                nameValue[0] = unescape( nameValue[0] ).replace(/\+/g,' ');
                values.push( nameValue );
            }
        }
    }

    return values;
}

function getParameterValues( queryString, parameterName )
{
    var values = [];

    if ( queryString != null && queryString.length > 0 )
    {
        var pairs = queryString.split( "&" );
    
        for ( var i = 0; i < pairs.length; i++ )
        {
            var pair = pairs[i];
            if ( pair != null && pair.length > 0 )
            {
                pair = unescape( pair );
                var nameValue = pair.split( "=" );
                if ( nameValue[0] == parameterName )
                {
                    if ( nameValue.length > 1 )
                    {
                        values.push( unescape( nameValue[1] ).replace(/\+/g,' ') );
                    }
                    else
                    {
                        values.push( "" );
                    }
                }
            }
        }
    }

    return values;
}

function updateFieldAsynchronously()
{
    if ( locatorPopup != null &&
         locatorPopup.fieldId != null &&
         locatorPopup.returnValue != null )
    {
        updateField( locatorPopup.fieldId,
                     locatorPopup.returnValue[0],
                     locatorPopup.returnValue[1] );
    }
}

function updateField( fieldId, fieldValue, displayValue )
{
    if ( fieldId != null )
    {
        if ( fieldValue == null || fieldValue == 'undefined' )
        {
            fieldValue = "";
        }

        if ( displayValue == null || displayValue == 'undefined' )
        {
            displayValue = "";
        }

        document.getElementById( fieldId ).value = fieldValue;
        document.getElementById( fieldId + ".display" ).value = displayValue;
    }
}

function __createPopUpContainer()
{
    // create container div
    var containerDiv = document.createElement( "DIV" );
    containerDiv.id = "__popUpContainer";
    containerDiv.className = "popUpContainer";
    containerDiv.style.width = findStyleSheetRule( ".popUpContainer", "width" );
    containerDiv.style.height = findStyleSheetRule( ".popUpContainer", "height" );

    // create body div
    var bodyDiv = document.createElement( "DIV" );
    bodyDiv.id = "__popUpBody";
    bodyDiv.className = "popUpBody";

    // create title div
    var titleDiv = document.createElement( "DIV" );
    titleDiv.id = "__popUpTitle";
    titleDiv.className = "popUpTitle";

    // create content div
    var contentDiv = document.createElement( "DIV" );
    contentDiv.id = "__popUpContent";
    contentDiv.className = "popUpContent";

    bodyDiv.appendChild( titleDiv );
    bodyDiv.appendChild( contentDiv );
    containerDiv.appendChild( bodyDiv );
    document.body.appendChild( containerDiv );
}

function setPopUpContent( content )
{
    var popUpContent = document.getElementById( "__popUpContent" );
    if ( popUpContent == null )
    {
        __createPopUpContainer();
        popUpContent = document.getElementById( "__popUpContent" );
    }
    popUpContent.innerHTML = content;
}

function positionElementByTrigger( element, trigger )
{
    //var trigger = Event.element( e ? e : window.event );
    var offsetLeft = 2;
    var offsetTop = -52;
    var triggerDimensions = Element.getDimensions(trigger);

    // in order to get dimensions, must display element
    element.style.left = "-1000px";
    element.style.top = "-1000px";
    element.style.display = "block";

    var triggerX = Position.cumulativeOffset(trigger)[0];
    var x = triggerX + triggerDimensions.width + offsetLeft;
    var triggerY = Position.cumulativeOffset(trigger)[1];
    var y = triggerY + trigger.offsetHeight + offsetTop;
    Position.prepare();
    var popUp = Element.getDimensions(element);
    if (x + popUp.width + offsetLeft > (Position.deltaX+Position.visibleWidth)) 
        x = Math.max( offsetLeft, ((Position.deltaX+Position.visibleWidth) - popUp.width - offsetLeft));
    if (y + popUp.height + offsetTop > (Position.deltaY+Position.visibleHeight)) {
        y = triggerY - popUp.height - offsetTop;
    }
    element.style.left = x+"px";
    element.style.top = y+"px";
}

function showPopUp( trigger, content )
{
    if ( content )
    {
        setPopUpContent( content );
    }

    var popUpContainer = document.getElementById( "__popUpContainer" );

    if ( popUpContainer == null )
    {
        __createPopUpContainer();
        popUpContainer = document.getElementById( "__popUpContainer" );
    }

    positionElementByTrigger( popUpContainer, trigger );
}

function hidePopUp( e )
{
    var ppopUpContainer = document.getElementById( "__popUpContainer" );
    if ( ppopUpContainer != null )
    {
        ppopUpContainer.style.display = "none";
    }
}

function __noop()
{
    return false;
}

function disableSubmit()
{
    var element = getSubmit();
    if ( element == null )
    {
        element = document.getElementById( "submitButton" );
    }
    if ( element != null )
    {
        //element.onclick=function(){ return false; };
        addEvent( element, "click", __noop, true );
        if ( element.value )
        {
            element.__value = element.value;
            element.value = "Please wait ...";
        }
        element.disabled = true;

        var image = document.getElementById( "loadingImage" );
        if ( image != null )
        {
            image.style.display = "block";
        }

        setTimeout( "enableSubmit()", 15000 );
    }
    return true;
}

function enableSubmit()
{
    var element = getSubmit();
    if ( element == null )
    {
        element = document.getElementById( "submitButton" );
    }
    if ( element != null )
    {
        element.disabled = false;
        if ( element.__value )
        {
            element.value = element.__value;
        }
        //element.onclick=function(){ return true; };
        removeEvent( element, "click", __noop, true );

        var image = document.getElementById( "loadingImage" );
        if ( image != null )
        {
            image.style.display = "none";
        }
    }
}

function setSubmit( element )
{
    document.__submitElement = element;
}

function getSubmit()
{
    return document.__submitElement;
}

function getFormFieldValue( form, fieldName )
{
    var value = null;

    var obj = form.elements[fieldName];
    if (obj)
    {
        if (obj.type == null ||
            obj.type == "radio")
        {
            for (var j = 0; j < obj.length; j++)
            {
                if (obj[j].checked)
                {
                    value = obj[j].value;
                    break;
                }
            }
        }
        else
        {
            switch (obj.type)
            {
            case "select-one":
                if (obj.selectedIndex != -1 )
                {
                    value = obj.options[obj.selectedIndex].value;
                }
                break;
            case "checkbox":
                if (obj.checked )
                {
                    value = obj.value;
                }
                break;
            case "select-multiple":
                break;
            case "text":
            case "textarea":
            case "hidden":
            case "password":
                value = obj.value;
                break;
            default:
            }
        }
    }
    return ( value != null ? value : "" );
}

function setFormFieldValue( form, fieldName, fieldValue )
{
    var value = null;

    var obj = form.elements[fieldName];
    if (obj)
    {
        if (obj.type == null ||
            obj.type == "radio")
        {
            for (var j = 0; j < obj.length; j++)
            {
                if (obj[j].value == fieldValue )
                {
                    obj[j].checked = true;
                    break;
                }
            }
        }
        else
        {
            switch (obj.type)
            {
            case "select-one":
                for (var j = 0; j < obj.options.length; j++)
                {
                    if (obj.options[j].value == fieldValue )
                    {
                        obj.options[j].selected = true;
                        break;
                    }
                }
                break;
            case "checkbox":
                if ( obj.value == fieldValue )
                {
                    obj.checked = true;
                }
                else
                {
                    obj.checked = false;
                }
                break;
            case "select-multiple":
                if ( typeof(fieldValue) == 'string' )
                {
                    fieldValue = [fieldValue];
                }
                for (var j = 0; j < obj.options.length; j++)
                {
                    for (var k = 0; k < fieldValue.length; k++)
                    {
                        if (obj.options[j].value == fieldValue[k] )
                        {
                            obj.options[j].selected = true;
                        }
                    }
                }
                break;
            case "text":
            case "textarea":
            case "hidden":
            case "password":
                obj.value = fieldValue;
                break;
            default:
            }
        }
    }
}


function getCookieVal (offset) 
{
    var endstr = document.cookie.indexOf (";", offset);

    if ( endstr == -1 )
        endstr = document.cookie.length;

    return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name) 
{
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;

    while ( i < clen )
    {
        var j = i + alen;

        if ( document.cookie.substring(i, j) == arg )
            return getCookieVal (j);

        i = document.cookie.indexOf(" ", i) + 1;

        if ( i == 0 )
            break;
    }

    return null;
}

function SetCookie (name, value) 
{

    var argv = SetCookie.arguments;
    var argc = SetCookie.arguments.length;
    var expires = (2 < argc) ? argv[2] : null;
    var path = (3 < argc) ? argv[3] : null;
    var domain = (4 < argc) ? argv[4] : null;
    var secure = (5 < argc) ? argv[5] : false;

    document.cookie = name + "=" + escape (value) +

                      ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +

                      ((path == null) ? "" : ("; path=" + path)) +

                      ((domain == null) ? "" : ("; domain=" + domain)) +

                      ((secure == true) ? "; secure" : "");

}

/**
 * Table list functions. The following variables should be set in
 * each page.
 */
var changePageUrl;
var editPageSizeUrl;
var applySortUrl;
var toggleSortUrl;
var removeSelectedRowsUrl;
var payoutOverrideSelectedRowsUrl;
var listPublishersSelectedRowsUrl;

function changePage( actionName )
{
    document.location = changePageUrl + actionName;
}

function editPageSize( pageSize )
{
    document.location = editPageSizeUrl + pageSize;
}

function applySort( columnName )
{
    document.location = applySortUrl + columnName;
}

function toggleSort( columnName )
{
    document.location = toggleSortUrl + columnName;
}

function removeSelectedRows( formName, tableName, confirmRemoval )
{
    var numRowsSelected = countSelectedRows( document.getElementById(tableName) );
    if ( numRowsSelected == 0 )
    {
        alert( "Please select at least one row to remove." );
    }
    else
    {
        var submit = confirmRemoval && confirm( "Are you sure you want to remove the " + numRowsSelected + " selected row(s)?" );
        if ( submit )
        {
            var form = document.forms[formName];
            form.action = removeSelectedRowsUrl;
            form.submit();
        }
    }
}

function moveOptionsRight( leftSelectId, rightSelectid )
{
	var leftSelect = $(leftSelectId);
	var rightSelect = $(rightSelectid);    
	var o = null;			

	for( i = 0; i < leftSelect.length; i++ )
    {
		o = leftSelect.options[i];
		if ( o.selected )
        {
			rightSelect.options[rightSelect.length] = new Option(o.text,o.value);
			leftSelect.options[i]=null;
			i--;
		}
	} 
}

function moveOptionsLeft( leftSelectId, rightSelectid )
{
	var leftSelect = $(leftSelectId);
	var rightSelect = $(rightSelectid);    
	var o;
	
	for( i = 0; i < rightSelect.length; i++ )
    {
		o = rightSelect.options[i];
		if ( o.selected )
        {
			leftSelect.options[leftSelect.length] = new Option(o.text,o.value);
			rightSelect.options[i]=null;
			i--;			
		}
	} 	
}

function payoutOverrideSelectedRows( formName, tableName, confirmOverride )
{
    var numRowsSelected = countSelectedRows( document.getElementById(tableName) );
    if ( numRowsSelected == 0 )
    {        
        alert( "Please select at least one row." );
    }
    else
    {
        var submit = confirmOverride && confirm( "Are you sure you want to override the payout on the " + numRowsSelected + " selected row(s)?" );
        if ( submit )
        {
            var form = document.forms[formName];
            form.action = payoutOverrideSelectedRowsUrl;
            form.submit();
        }
    }
}

function listPublishersSelectedRows( formName, tableName, confirmOverride )
{
    var numRowsSelected = countSelectedRows( document.getElementById(tableName) );
    if ( numRowsSelected == 0 )
    {        
        alert( "Please select at least one row." );
    }
    else
    {
        var submit = confirmOverride;
        if ( submit )
        {
            var form = document.forms[formName];
            form.action = listPublishersSelectedRowsUrl;
            form.submit();
        }
    }
}

function autotab(original,destination)
{
        if (original.getAttribute&&original.value.length==original.getAttribute("maxlength"))
        destination.focus()
}

function isValid3PartPhone( form, prefix )
{
    var phone = '' + form.elements[prefix+'Part1'].value + form.elements[prefix+'Part2'].value + form.elements[prefix+'Part3'].value;

    return phone.match( /[0-9]{10}/ );
}

/* Bridge XMLHTTP to XMLHttpRequest in pre-7.0 Internet Explorer */
if ( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
        try
        {
            return new ActiveXObject("Msxml2.XMLHTTP.6.0")
        }
        catch( e )
        {
        }
        try
        {
            return new ActiveXObject("Msxml2.XMLHTTP.3.0")
        }
        catch( e )
        {
        }
        try
        {
            return new ActiveXObject("Msxml2.XMLHTTP")
        }
        catch( e )
        {
        }
        try
        {
            return new ActiveXObject("Microsoft.XMLHTTP")
        }
        catch( e )
        {
        }
        return null;
    };

function swapOptions( optionMap, source, target )
{
    target.options.length = 0;

    var selectedValue = source.selectedIndex != -1 ? source.options[source.selectedIndex].value : null;
    if ( selectedValue != null && selectedValue.length > 0 )
    {
        target.options[0] = new Option( "-- select one --", "" );

        var optionPairs = optionMap[selectedValue];
        for ( var i = 0; i < optionPairs.length; i++ )
        {
            var pair = optionPairs[i];
            var selected = pair.length >= 3 ? pair[2] : false;
            target.options[target.options.length] = new Option( pair[1], pair[0], false, selected );
            //createOption( pair[0], pair[1], selected, target );

        }
        target.options[0].disabled = false;
    }
    else
    {
        target.options[0] = new Option( "-- select one --", "" );
        target.options[0].disabled = true;
    }
}

function createOption(strVal,strText,selected,objTargetSelect)
{
    var opt = document.createElement('OPTION');
    opt.setAttribute('value',strVal);
    if (selected)
    {
        opt.setAttribute('selected','true');
    }
    var text = document.createTextNode(strText);
    opt.appendChild(text);
    objTargetSelect.appendChild(opt);
}
