var g_initialState = '';
var thisnav = '';

if ( typeof window.addEventListener != "undefined" )
{
    // DOM2
    window.addEventListener( "load", SetExternalLinks, false );
    window.addEventListener( "load", replaceImgInputs, false );
} 
else if ( typeof window.attachEvent != "undefined" ) 
{
    // IE
    window.attachEvent( "onload", SetExternalLinks );
    window.attachEvent( "onload", replaceImgInputs );
} else {
    if ( window.onload != null ) 
    {
        var oldOnload = window.onload;
        window.onload = function ( e ) 
        {
            // function_call();
            SetExternalLinks();
            replaceImgInputs();
            oldOnload;
        }
    } else {
        window.onload = '';
    }
}

function SetExternalLinks()
{
    var links = new Array();
    links = document.links;
    for ( i=0; i<links.length; i++ )
    {
        var href = links[i].href;
        if (  typeof href != "undefined" )
        {
            var href = new String( href );
            var baseuri = base_uri;
            baseuri.replace( 'http://', null );
            if ( href.indexOf( baseuri ) == -1 &&
                 href.indexOf( 'javascript' ) == -1 &&
                 href.indexOf( 'skype:' ) == -1 )
            {
                links[i].href = 'javascript: void OpenWindow( \'' + href + '\' );';
            }
        }
    }
}

OpenWindow = function( url )
{
    var attrs = 'menubar=1,directories=1,toolbar=1,resizable=1,location=1,scrollbars=1';
    PopWin = window.open( url, '', attrs );
}

function sniff( str )
{
    var ua = navigator.userAgent.toLowerCase();
    
    if ( ua.indexOf( str ) != -1 )
    {
        return 1;
    }
    return 0;
}

function isOperaOrIE()
{
    var ua = navigator.userAgent.toLowerCase();

    if ( ua.indexOf( 'opera' ) != -1 )
    {
        return 1;
    } else if ( window.ActiveXObject ) {
        return 2;
    } else {
        return 0;
    }
}

function replaceImgInputs()
{
    var btns;
    var btn;

    if ( ua = isOperaOrIE() > 0 )
    {
        btns = document.getElementsByTagName('input');
        
        for ( i=0; i<btns.length; i++ )
        {
            btn = btns[i];
            if ( btn.type == 'image' )
            {
                btn['onclick'] = addSubmitButton;
            }
        }
    }

}

addSubmitButton = function()
{
    var myInput;
    
    if ( myInput = document.createElement( 'input' ) )
    {
        
        // I am aware that the correct way to not display
        // the input we are creating is to set its 'type'
        // to 'hidden' but IE5 for Mac will not allow
        // the script to set the type of the input.
        //
        // This is, as far as I can tell, a bug in IE5 Mac
        // (no big surprise there).
        
        myInput.style.display = 'none';
        myInput.name  = 'submit';
        myInput.value = this.value;
        this.parentNode.appendChild( myInput );
    }
}

function setStoryName( storyname ) {
    document.forms[0].story.value = storyname;
}

function submitForm( idx ) {
    document.forms[idx].submit();
}

function checkSelection( idx, selector, msg )
{
    selector = document.forms[idx][selector];
    selection = selector.options[selector.selectedIndex].value;
    
    if ( selection == '' ) {
        alert( 'Please select a '+msg+'.' );
        return false;
    } else {
        return true;
    }

}

function nonEmptyField( thefield, msg )
{
    theform = document.forms[0];
    if ( trim( theform[thefield].value ) == '' ) {
        alert( msg );
        return false;
    }
    return true;
}

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

function confirmDelete( what, canUndo )
{
    var msg = 'Are you sure you want to delete '+what+'? ';
    if ( canUndo == 1 ||
          canUndo == true ||
          canUndo == 'true' )
    {
        msg += 'You can restore this item with the Trash Manager control.';
    }
    else
    {
        msg += 'This change cannot be undone.';
    }
    return confirm( msg );    
}

function validatePasswordChange( myForm )
{
    var myNewUser = myForm['username'].value;
    var myNewPass = myForm['password'].value;
    var myPassConfirm = myForm['confirm'].value;
    
    if ( myNewUser == '' )
    {
        alert( 'You must enter a username.');
        return false;
    }
    
    if ( myNewPass == '' )
    {
        alert( 'You must enter a password.' );
        return false;
    }
    
    if ( myPassConfirm == '' )
    {
        alert( 'You must confirm your password.' );
        return false;
    }
    
    if ( myNewPass != myPassConfirm )
    {
        alert( 'Password Confirmation failed. Please re-enter your new password.' );
        return false;
    }
    else
    {
        myForm.submit()
    }
}

function initStoryState( whicheditor )
{
    if ( whicheditor.indexOf('mce') != -1 ) 
    {
        tinyMCE.execCommand('mceFocus', 0, whicheditor);
        g_initialState = tinyMCE.getContent()
    } 
    else 
    {
        g_initialState += getFormState();
    }
}

function checkStoryState( whicheditor )
{
    tinyMCE.execCommand('mceFocus', 0, whicheditor);
    return tinyMCE.getContent();
}

function joinArray( arr ) {
    // Need to write a generic function to join an array
}

function getFormState ( ) {
    var myState = '';
    for ( i=0; i<document.forms.length; i++ )
    {
        thisform = document.forms[i];
        for ( j=0; j<thisform.length; j++ )
        {
            var thisvalue = thisform[j].value;
            if ( thisvalue ) {
                thisvalue.toUpperCase();
            }
            if ( thisform[j].type == 'file' ||
                  thisform[j].type == 'text' ||
                  thisform[j].type == 'textarea' )
            {
                myState += thisvalue;
            }
        }
    }
    return myState;
}

function confirmPageChange( myTask, whicheditor ) {
    if ( myTask.toLowerCase() != 'editor' )
    {
    var newState = getFormState();
    }
    else
    {
    var newState = checkStoryState( whicheditor );
    }
    if ( newState != g_initialState )
    {
        return confirm('Do you want to discard the changes to the current page?');    
    }
}

function confirmDiscard( whicheditor, whichSelector, curSelection ) {
    var newSelection = whichSelector.options[whichSelector.selectedIndex].value;
    if ( newSelection == curSelection ) {
        return false;
    }
    if ( newSelection != 0 && 
          newSelection != '0' && 
          newSelection != '' )
    {
        var currentState = checkStoryState( whicheditor )
        if ( currentState != g_initialState ) {
            var myResponse = confirm('Do you want to discard the changes to the current story?');    
            if ( myResponse == 'false' || 
                 myResponse == 0 
               ) {
                return false;
            }
            changeloc( whichSelector );
        }
        changeloc( whichSelector );
    }
}

function toggleImgSrc( which, isrc, fromwhat, towhat ) {
    if ( isrc.indexOf(fromwhat) != -1 ) {
        which.src = isrc.replace(fromwhat,towhat);
    } else {
        which.src = isrc.replace(towhat,fromwhat);
    }
}

function changeClassName( which, whichchild, towhat ) {
    for(i=1; i< which.childNodes.length; i++) {
      node = which.childNodes[i];
      if( node.nodeName == whichchild ) {
          if ( node.className.indexOf(towhat) != -1 ) {
                node.className=node.className.replace(towhat,'');
            } else {
                node.className+=towhat;
            }
      }
    }
}

function markmeactive( which )
{
  ;
}

function Show( which ) {
    clearTimeout( timerID );
    for(i=1; i< which.childNodes.length; i++) {
      node = which.childNodes[i];
      if( node.nodeName == "UL" ) {
          if ( node.className.indexOf("_show") == -1 ) {
            node.className += "_show";
        }
      }
    }
}

function hide( which ) {
    for(i=1; i< which.childNodes.length; i++) {
      node = which.childNodes[i];
      if( node.nodeName == "UL" ) {
          node.className = node.className.replace( "_show", "" );
      }
    }
}

function hideCountdown(){
      timerID = setTimeout("hide(thisnav)",500);
}

function setBackgroundImage( which, what, w, h ) {
    // document.images[which].src = what;
    document.getElementById(which).style.backgroundImage    = "url("+what+")";
    document.getElementById(which).style.width                = w;
    document.getElementById(which).style.height                = h;
}

function setimage( which, what ) {
    document.images[which].src = what;
}

function settext ( whichid, whattext ) {
    document.getElementById(whichid).innerHTML=whattext;
}

function changeloc( URL_List ) {
    var URL = URL_List.options[URL_List.selectedIndex].value;
    if ( URL != 0 && URL != '0' ) {
        // URL += '.html';
       window.location.href = URL;
   }
}

function formvalidate( myform, myfields ) {
    emptyalert = 'You did not provide a(n) ';
    emailalert = 'The email entered does not appear to be a valid format.';
    for ( i=0; i<myfields.length; i++ ) {
        var myfield = myfields[i];
        if ( document.forms[myform][myfield].value == '' ) {
            alert(emptyalert+myfield);
            return false;
        }
        if ( myfield.indexOf('email') != -1 ) {
            if ( ( document.forms[myform][myfield].value.search("@") == -1 ) || 
                  ( document.forms[myform][myfield].value.search("[.*]" ) == -1 ) ) {
                alert(emailalert);
                return false;
            }
        }
    }
    document.forms[myform].submit();
}

/* STYLE SHEET SWITCHER FUNCTIONS */

function setActiveStyleSheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
}

function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}

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 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;
}
