//
// These track the type of browser that is being used, and can be tested for, so that JavaScript can be
// tweaked accordingly.
//
var isIe = false;
var isIE4p = false;
var isIE7 = false;
var isMozilla = false;
var isOpera = false;
var isSafari = false;

var bDialogIsActive = false;
var activeFCKEdit = "";
  
var loginWebSvcUrl = "/bbphotoadminlogin.php";
var loginPopupDlg = null;
var logoutPopupDlg = null;
var currSecurityKey = "";
  
  function doLoginForm( pageName )
  {
	  //
	  // Only one dialog may be active at a time...
	  //
	  if( loginPopupDlg != null )
	  {
		  return false
	  }

      var content = 
          "<form class='bbphotologinform' action='" + loginWebSvcUrl + "' id='userloginform' method='post' target='hiddenloginlogoutiframe'>" +
          "<table class='bbphotologinformtable'>" +
          "<tr><td class='bbphotologinformusrnamehdg'>User Name:</td><td><input type='text' name='usrname' id='bbphotousrname' value='' size='20' class='bbphotologinformusrnameinpt'/></td></tr>" +
          "<tr><td class='bbphotologinformpasswdhdg'>Password:</td><td><input type='password' name='passwd' id='bbphotopasswd' value='' size='20' class='bbphotologinformpasswdinpt'/></td></tr>" +   
          "</table>" +
          "<input type='hidden' name='logintype' value='" + pageName + "'>" +
          "<input type='button' name='Ok' value='Ok' id='imgeditsave' class='bbphotologinformok' onClick='doUserLogin();return false;'>" +
	      "<input type='button' name='Cancel' value='Cancel' id='imgeditcancel' class='bbphotologinformcancel' onClick='hideAlbumLoginBox();return false;'>" +
	      "</form>";

      loginPopupDlg = new Popup( document.body.scrollLeft + 100, document.body.scrollTop + 100, 290, 130 ,"User Login", "FOCUS|MOVE|MODAL", content );  
      loginPopupDlg.show(); 
      loginPopupDlg.onClose( function() {bDialogIsActive=false;loginPopupDlg = null;} );
      bDialogIsActive = true;
      
	  if (document.getElementById("userloginform").attachEvent)
      {
          loginPopupDlg.wrapper.attachEvent("onkeypress",doLoginKeypress);
          document.getElementById("bbphotousrname").attachEvent("onkeypress",doLoginKeypress);
          document.getElementById("bbphotopasswd").attachEvent("onkeypress",doLoginKeypress);
   	  }
      else if( document.getElementById("userloginform").addEventListener )
      {
          loginPopupDlg.wrapper.addEventListener("keypress",doLoginKeypress, false);
          document.getElementById("bbphotousrname").addEventListener("keypress",doLoginKeypress, false);
          document.getElementById("bbphotopasswd").addEventListener("keypress",doLoginKeypress, false);
      }
      else
      {
          alert('Unable to set keypress event handler.');
      }
      
      setTimeout( function() { document.getElementById("bbphotousrname").focus(); document.getElementById("bbphotousrname").select(); }, 10 );
  }
  
  function doLoginKeypress(e)
  {
	  var code = 0;
	  var targ = null;
	  
	  if( !e ) e = window.event;
	  
	  if (e.keyCode) code = e.keyCode;
	  else if (e.which) code = e.which;
	  
	  if (e.target) targ = e.target;
	  else if (e.srcElement) targ = e.srcElement;
	  if (targ.nodeType == 3) // defeat Safari bug
	     targ = targ.parentNode;
	  
      if( code == 13 )
      {
         if( targ.id == 'bbphotousrname')
         {
            setTimeout("document.getElementById('bbphotopasswd').focus();",1);      	    
      	 }
      	 else if( targ.id == 'bbphotopasswd')
         {
            doUserLogin();         
         }
      }
      else if( code == 27 )
      {
	     hideAlbumLoginBox();
      }
      else
      {
         return true;
      }
         
      return false;   
  }
  
  var loginInProgress = false;
  
  function doUserLogin()
  {  		  
      var userloginform = document.getElementById('userloginform');
      if( userloginform )
      {
          try
          {
              var params = "usrname="+ urlencode(userloginform.usrname.value) +
                            "&passwd="+ urlencode(userloginform.passwd.value) +
                            "&logintype="+ urlencode(userloginform.logintype.value);
          
              if( loginInProgress )
                  return;
           
              loginInProgress = true;
          
              sendAjaxRequest( params, loginWebSvcUrl , function(responseXML){
              
                  // look for the h3 with the id of 'success' if there, continue, else pop up error alert.
                  if( null != responseXML.getElementsByTagName('success')[0] )
                  {                  
                      hideAlbumLoginBox();
                  }
                  else
                  {
                      var errorMsgNode = responseXML.getElementsByTagName('error')[0]
                      if( null != errorMsgNode )
                      {
                          var errorText = getTextNode(errorMsgNode);
                          alert( errorText );
                      }                      
                  }
                     
                  loginInProgress = false;         
              } );
              
          }
          catch( err ) {
	          alert('Unable to log in. XHR failed.');
	          hideAlbumLoginBox();
              loginInProgress = false;         
	      }	      
      }
  }

function hideAlbumLoginBox()
{
	if( loginPopupDlg != null )
	{
	    loginPopupDlg.close();
		loginPopupDlg = null;
	}	  
}
  
function requestLogout(logouttype)
{
    if( logoutPopupDlg != null )
	{
	    return false
	}

    var logoutform =	  
        "<form class='bbphotologoutform' action='" + loginWebSvcUrl + "' id='userlogoutform' method='post' target='hiddenloginlogoutiframe'>" +
        "<span class='prompt'> Are you sure you wish to log out? </span><br> " +
        "<input type='hidden' name='logintype' value='" + logouttype + "'>" +
        "<input type='button' name='Yes' value='Yes' id='logoutbtn' class='buttonyes' onClick='doUserLogout();return false;'>" +
	    "</form>";

    logoutPopupDlg = new Popup( document.body.scrollLeft + 100, document.body.scrollTop + 100, 290, 110 ,"Confirm Log out", "FOCUS|MOVE|MODAL",logoutform );  
    logoutPopupDlg.onClose( function() { logoutPopupDlg = null;bDialogIsActive = false; } );
    logoutPopupDlg.show();
    bDialogIsActive = true;

	if (document.getElementById("userlogoutform").attachEvent)
    {
        logoutPopupDlg.wrapper.attachEvent("onkeypress",doLogoutKeypress);
   	}
    else if( document.getElementById("userlogoutform").addEventListener )
    {
        logoutPopupDlg.wrapper.addEventListener("keypress",doLogoutKeypress, false);
    }
}

function doLogoutKeypress(e)
{
    var code = 0;
	var targ = null;

	if( !e ) 
	{
	    e = window.event;
	}

	if (e.keyCode) 
	{
	    code = e.keyCode;
	}
	else if (e.which) 
	{
	    code = e.which;
	}

    if( code == 27 )
    {
	    logoutPopupDlg.close();
    }
    else
        return true;
}
  
function doUserLogout()
{
    if( logoutPopupDlg )
    {
    
        var logintype = document.getElementById('userlogoutform').logintype.value;
        try
        {
            var params = "action=userLogOut";
          
            sendAjaxRequest( params, loginWebSvcUrl , function(responseXML){ currSecurityKey=""; } );              
        }
        catch( err ) 
        {
	        alert('Unable to log out. XHR failed.');
	    }	   

  	    logoutPopupDlg.close();
  	      
        var adminitm = document.getElementById('bbphotoadminitm');
		
		var newAdminStr = "<a id=\"bbphotologinbtn\" onClick=\"doLoginForm('" + logintype + "'); return false;\"><img src='/log_in.png' alt='[Log In]'></a>";
		
	    adminitm.innerHTML = newAdminStr;	  
	    currSecurityKey = "";
    }
}  
  
//
// Used for form based file uploads...
//
function checkIframeError(oIframe)
{		    		    
    if( bDialogIsActive )
	{
	    var error = true;
	    var errString = "An unknown error has occurred.";
		   
		try 
		{
		    var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
		    if (oDoc.document) oDoc = oDoc.document;
		    if(oDoc.getElementById('success') ) error = false;		
		    if(oDoc.getElementById('error') )
    		    errString = getTextNode(oDoc.getElementById('error'));		    			    
		}
		catch( ex ) 
		{
		    errString = "A network error / timeout has occurred.";
		}
		       
		if( error )
		{
		    setTimeout("alert( \""+ errString +"\\n Please try again later.\"); ",10);				
	    }	     
	}	   
}
 
function setNewKey( tstKey, newKey )
{
    if( tstKey == currSecurityKey )
    {
        currSecurityKey = newKey;
    }
}

function createCookie(name,value,days) 
{
    var expires = "";
	if (days) 
	{
	    var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		  
		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;
}

function eraseCookie(name) 
{
	createCookie(name,"",-1);
}

//
// This method sets a series of flags that can be used elsewhere to
// provide browser-specific fixups and variations in the JavaScript.
//
function getBrowserType()
{
    var agt = navigator.userAgent.toLowerCase();
    var is_major = parseInt(navigator.appVersion);
    var is_minor = parseFloat(navigator.appVersion);

    isIe = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
    if( isIe && is_major >= 4 )
    {
        isIE4p = true;
    }
    if( isIe && window.XMLHttpRequest )
    {
        isIE7 = true;
    }

    isMozilla = (agt.indexOf("firefox") != -1) ||
                ((agt.indexOf("gecko") != -1) && (agt.indexOf("safari") == -1));

    isOpera = (agt.indexOf("opera") != -1);

    isSafari = (agt.indexOf("safari") != -1);

    return true;
}


function getTextNode( element )
{
    var returnedText = "";

    if( element )
    {
        if( element.textContent )
        {
            returnedText = element.textContent;
        }
        else if( element.text )
        {
            returnedText = element.text;
        }
    }

    if( returnedText.indexOf("[CDATA[") > -1 )
    {
        returnedText = returnedText.substring(7);
    }

    if( returnedText.lastIndexOf("]]") > -1 )
    {
        returnedText = returnedText.substring(0, returnedText.lastIndexOf("]]") );
    }

    return returnedText;
}

function createXMLHttpRequest()
{
    if (typeof XMLHttpRequest != "undefined")
    {
        return new XMLHttpRequest();
    }
    else if (typeof ActiveXObject != "undefined")
    {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    else
    {
        throw new Error("XMLHttpRequest not supported");
    }
}

function sendAjaxRequest( params, application , callbackFn )
{
    var xhtObj = createXMLHttpRequest();

    showWaitCursor();
           
    params = params + "&key=" + currSecurityKey;

    xhtObj.open("POST", application, true);
    xhtObj.onreadystatechange = function()
    {
        if (xhtObj.readyState == 4)
        {
            if( xhtObj.responseXML != null )
            {
                var baseresp = xhtObj.responseXML.getElementsByTagName('response')[0];
                
                if( null == currSecurityKey || currSecurityKey == "" || baseresp.getAttribute("auth") == currSecurityKey )
                { 
                    // Set the new authentication code (if any).               
                    if( baseresp.getElementsByTagName('newauth').length > 0 )
                    {
                        currSecurityKey = getTextNode(baseresp.getElementsByTagName('newauth')[0]);
                    }

                    // Find all script elements and execute them. 
                    var scriptElements = xhtObj.responseXML.getElementsByTagName('script');
                  
                    for( var idx = 0; idx < scriptElements.length; ++idx )
                    {
                        var scriptText = getTextNode(scriptElements[idx]);
                          
                        // Eval all script elements.
                        eval(scriptText);                           
                    }    
                    
                    callbackFn (xhtObj.responseXML);
                }
            }
                            
            hideWaitCursor();

        }
    }

    xhtObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhtObj.setRequestHeader("Content-length", params.length);
    xhtObj.setRequestHeader("Connection", "close");
    xhtObj.send(params);
}

function showWaitCursor()
{
    var waitcursor = document.getElementById('waitcursor');
    if( !waitcursor )
    {
        waitcursor = document.createElement("img");
        waitcursor.style.display='none';
        document.body.appendChild(waitcursor);
    }
    
    waitcursor.src='loading.gif';
    waitcursor.id='waitcursor';
    waitcursor.style.position='absolute';
    waitcursor.style.width='64px';
    waitcursor.style.height='64px';
    waitcursor.style.top= (getWindowSize().height / 2 - 32) +'px';     // hack for now
    waitcursor.style.left= (getWindowSize().width / 2- 32) +'px';    // hack for now
    waitcursor.style.zIndex=10000;
    waitcursor.style.display='block';
}

function hideWaitCursor()
{
    var waitcursor = document.getElementById('waitcursor');
    if( waitcursor )
    {
        document.body.removeChild(waitcursor);
    }
}

function urlencode( str ) 
{
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
                             
    var histogram = {}, tmp_arr = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urldecode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    return ret;
}
