// Initialize page stuff
jQuery(document).ready( function() {

   breakout();

   // Init the sign-in window
   jQuery("#idSignIn").bind( "click", function( aEvent ) {
   
      // Hide any open alerts
      hideAlert();
      
      // Set the timezone offset
      jQuery("input[name='aTimezoneOffset']").val( new Date().getTimezoneOffset() );
   
      // Open and position the window, then gracefully show it
	   jQuery("#idDivSignIn").css({
         left: jQuery(this).offset().left - jQuery("#idDivSignIn").width() + 115,
         top: jQuery(this).offset().top + 23
	   })
	   .show( "normal", function () {
	      jQuery("#idSignInEmail").select();
	      
	      // Hide the sign-in div once the user clicks away
         jQuery(document).one( "click", function(f) {
            jQuery("#idDivSignIn").hide();
         });
         
         // STOP the sign-in window from disappearing when it is clicked
         jQuery(this).bind("click", function(e) { e.stopPropagation(); });
	   });
	   
	   // Stops the following click function from being executed
	   aEvent.stopPropagation();
   });
});

// Detetcts if we're in a frame or proxy, and breaks out
function breakout()
{
   var lCurrentUrl = String(window.top.location).toLowerCase();
   if ( window.top.location != location || !isUrlValid(lCurrentUrl) ) {
      window.top.location.replace("http://www.pairpeople.com");
   }
}

// Checks to see if the passed in url is of a valid domain
function isUrlValid( aUrl ) {
   var lValidUrls = ["http://www.pairpeople.com", "http://pairpeople.com", "http://localhost/"];
   for ( var i = 0; i < lValidUrls.length; i++ ) {
      if ( aUrl.indexOf( lValidUrls[i] ) == 0 ) {
         return true;
      }
   }
   return false;
}

// Starts monitoring for chat requests
var iChatMonitor = null;
function startChatMonitor()
{
   iChatMonitor = new ChatMonitor();
   iChatMonitor.start();
}

// Generates a new captcha img
function generateNewCaptcha( aImgId )
{
   jQuery("#" + aImgId).attr("src", "/servlet/Captcha?aTime=" + new Date().getTime() );
}

// Formats the time properly
function getFmtTime()
{
   var lDate = new Date();
   var lHours = lDate.getHours();
   var lMins = lDate.getMinutes();
   
   var lAm
   if ( lHours == 0 ) {
      lAm = " AM";
      lHours = 12;
   }
   else if ( lHours <= 11 ) {
      lAm = " AM"
   }
   else if ( lHours == 12 ) {
      lAm = " PM";
   }
   else if ( lHours >= 13 ) {
      lAm = " PM";
      lHours -= 12;
   }
   
   return lHours + ":" + lMins + lAm;
}

// Opens a custom alert
function customAlert( aTitle, aMessage, aCallback )
{
   // Unbind any leftover click events
   jQuery("#idAlert1Button").unbind("click").click( function() { hideAlert(); } );

   // Set the text on buttons
   jQuery("#idAlert1Button").html("&nbsp;&nbsp;&nbsp;OK&nbsp;&nbsp;&nbsp;");
   
   // Hide the second button that should be hidden by default in case customConfirm() was called
   jQuery("#idAlert2Button").hide();
   
   // Set title
   if ( aTitle != null ) {
      jQuery("#idAlertTitle").html( aTitle );
   }

   // Set the alert message
   jQuery("#idAlertMessage").html( aMessage );
   
   // If there's a callback function, add it to the onclick of the button
   if ( typeof aCallback != "undefined" && aCallback != null ) {
      jQuery("#idAlert1Button").one( "click", aCallback );
   }
   
   // Center and show the alert dialog
   var lAlert = jQuery("#idAlertDiv");
   lAlert.center( true ).css("z-index", "9999").show();
   
   // Show blocking iframe
   showBlocker( lAlert );
   
   // Set the focus on the ok button
   jQuery("#idAlert1Button").focus();
}

// Opens a custom confirm dialog
function customConfirm( aTitle, aMessage, aYesCallback, aNoCallback )
{
   // Unbind any leftover click events
   jQuery("#idAlert1Button").unbind("click").click( function() { hideAlert(); } );
   jQuery("#idAlert2Button").unbind("click").click( function() { hideAlert(); } );

   // Set the text on buttons
   jQuery("#idAlert1Button").html("&nbsp;&nbsp;Yes&nbsp;&nbsp;");
   jQuery("#idAlert2Button").html("&nbsp;&nbsp;No&nbsp;&nbsp;");
   
   // Show the second button that hidden by default
   jQuery("#idAlert2Button").show();
   
   // Set title
   if ( aTitle != null ) {
      jQuery("#idAlertTitle").html( aTitle );
   }

   // Set the confirm message
   jQuery("#idAlertMessage").html( aMessage );
   
   // There must always be a yes callback
   jQuery("#idAlert1Button").one( "click", aYesCallback );

   // If there's a no callback function, add it to the onclick of the button
   if ( typeof aNoCallback != "undefined" ) {
      jQuery("#idAlert2Button").one( "click", aNoCallback );
   }
   
   // Center and show the confirm dialog
   var lAlert = jQuery("#idAlertDiv");
   lAlert.center( true ).css("z-index", "9999").show();
   
   // Show blocking iframe
   showBlocker( lAlert );
}

// Position blocking iframe and show it
function showBlocker( aObject )
{
   // Position the blocking iframe, only if IE6!
   if ( isIE6() ) {
      var lPosition = aObject.position();
      jQuery("#idBlockFrame")
         .width( aObject.outerWidth() )
         .height( aObject.outerHeight() )
         .css( "top", lPosition.top )
         .css( "left", lPosition.left )
         .show();
   }
}

// Hides the alert div
function hideAlert()
{
   hideBlocker();
   jQuery("#idAlertDiv").hide();
}

// Hides the blocker iframe
function hideBlocker()
{
   jQuery("#idBlockFrame").hide();
}

// Adds a bubble tip to a textfield that appears onfocus
function initBubble( aObject, aMessage )
{
   var lBubble = jQuery("#idBubbleDiv");
   
   jQuery(aObject).one("focus", function() {
      lBubble.html( aMessage ).css({
         left: jQuery(this).offset().left + jQuery(aObject).width() - 40,
         top: jQuery(this).offset().top - lBubble.height() - 25
      }).show();
      showBlocker( lBubble );
   });
   
   jQuery(aObject).one("blur", function() {
      hideBlocker();
      lBubble.hide();
   });
}

// Opens the report user window
function openReportUser( aUserEncrypt, aDisplayName )
{
   var lBody = jQuery("textarea[name='aReportDescription']");
   lBody.val("");
   jQuery("#idReportDisplayName").html(aDisplayName);
   jQuery("#idReportSubmitBtn").unbind("click").bind("click", function() {
      Message.reportUser(
            aUserEncrypt,
            jQuery("select[name='aReportType']").val(),
            lBody.val(), function() {
         closeDimMsg();
         customAlert( "Thank you", "Your report has been submitted." );
      });
   });
   showDimMsg( jQuery("#idReportDiv"), 325, 410 );
}

// Goes back in the browser by one if there is a history
function back()
{
   if ( window.history.length == 0 ) {
      customAlert( "Error", "Sorry you can't use the back button because there's nothing in your history." );
   } else {
      window.history.back();
   }
}

// Shows a message to a user if they try to search while not logged in
function searchMsg( aReason )
{
   if ( aReason == "NOT_SIGNED_IN" ) {
      customAlert( "Sign In", "You must be signed in to perform advanced searches.<br><br>Please <a href='#' onclick='jQuery(\"#idSignIn\").click(); return false;'>sign in</a> or <a href='/Register.jsp'>create a new account</a>." );
   } else if ( aReason == "NOT_VALIDATED" ) {
      showMustValidateMessage();
   } else {
      showLimitedUseMessage();
   }
}

// Shows a generic message about having limited use until profile details are provided
function showLimitedUseMessage()
{
   customAlert( "Profile Details Required", "Sorry, but you have to provide a few more details to your profile before you can fully use the site.<br><br>Please <a href='/in/EditProfile.jsp'>click here</a> to edit your profile." );
}

// Shows a generic message about having limited use until email validated
function showMustValidateMessage()
{
   customAlert( "Please Validate Email", "Sorry, but you have to validate your email address before you can fully use the site.<br><br>Please go to <a href='/in/Inbox.jsp'>My Home</a> and look for the 'Important' message to correct this problem." );
}

// Message to show when the users account has been disabled, they have a warning
function showDisabledMessage()
{
   customAlert( "Error", "You have been issued a warning from the site Administrators.<br><br>Please go to <a href='/in/Inbox.jsp'>My Home</a> to correct the warning and re-enable your account." );
}

// Redirect the user back to the homepage after the session expiry timeout
function sessionRedirect()
{
   if ( window.location.pathname != "/" ) {
      setTimeout( "window.location.href='/servlet/SignOut'", 25 * 60 * 1000 );
   }
}

// Pops up a msg window with a dimmed background
var iDimmerDiv = null;
var iDimmerMsg = null;
function showDimMsg( aMsgDiv, aHeight, aWidth, aCallBack )
{
   // If another dimmer message was open, hide just the message
   if ( iDimmerMsg != null ) {
      iDimmerMsg.hide();
   }
   
   // If we haven't created the dimmer div yet, create it
   if ( iDimmerDiv == null ) {
      iDimmerDiv = jQuery( "<div></div>" )
         .addClass( "dimmer" )
         .height( jQuery(document).height() )
         .width( jQuery(document).width() )
         .appendTo( document.body );
   } else {
      iDimmerDiv
         .height( jQuery(document).height() )
         .width( jQuery(document).width() )
         .show();
   }
   
   // Resize the dim div if the window resizes
   jQuery(window).bind( "resize", function(e) {
      iDimmerDiv
        .height( jQuery(document).height() )
        .width( jQuery(document).width() );
   });
   
   // Create the message
   iDimmerMsg = jQuery( aMsgDiv )
      .addClass( "dimmermsg" )
      .prop( "scrollTop", "0" )
      .height( aHeight )
      .width( aWidth )
      .center()
      .show( "fast", aCallBack );
}

// Closes the dimmed message window
function closeDimMsg()
{
   if ( iDimmerMsg != null ) {
      iDimmerMsg.hide();
   }
   if ( iDimmerDiv != null ) {
      iDimmerDiv.hide();
   }
}

// Image object
function Image( aIndex, aId, aWidth, aHeight, aDescription, aIsPrivate )
{
   this.index = aIndex;
   this.id = aId;
   this.width = aWidth;
   this.height = aHeight;
   this.description = aDescription;
   this.isPrivate = aIsPrivate;
}

// Sets the max length on text area fields
function setMaxLength() {
   var x = document.getElementsByTagName('textarea');
   var counter = document.createElement('div');
   for (var i=0;i<x.length;i++) {
      if (x[i].getAttribute('maxlength')) {
         var counterClone = counter.cloneNode(true);
         counterClone.relatedElement = x[i];
         counterClone.innerHTML = '<span>0</span>/'+x[i].getAttribute('maxlength');
         x[i].parentNode.insertBefore(counterClone,x[i].nextSibling);
         x[i].relatedElement = counterClone.getElementsByTagName('span')[0];
         x[i].onkeyup = x[i].onchange = x[i].onfocus = checkMaxLength;
         x[i].onkeyup();
      }
   }
}

// Checks to see if we've reached the max length on text area fields
function checkMaxLength() {
   var maxLength = this.getAttribute('maxlength');
   var currentLength = this.value.length;
   if (currentLength > maxLength) {
      this.value = this.value.substr(0, maxLength);
      currentLength = maxLength;
   } else {
      this.relatedElement.className = '';
   }
   this.relatedElement.firstChild.nodeValue = currentLength;
   // not innerHTML
}

// Adds a new window.onload event
function addWindowOnLoadEvent( func ) {
   var oldonload = window.onload;
   if ( typeof window.onload != 'function' ) {
      window.onload = func;
   } else {
      window.onload = function() {
         oldonload();
         if( func ) { func(); }
      }
   }
}

// Opens up a modal window
function openWin( aUrl, aName, aWidth, aHeight, aModal, aScroll ) {
   if ( 1 == 2 && window.showModalDialog && aModal ) {
      window.showModalDialog( aUrl, aName, "dialogWidth:" + aWidth + "px;dialogHeight:" + aHeight + "px;status:no;scroll:no;" );
   } else {
      var lLeft = ( screen.width - aWidth ) / 2;
      var lTop = ( screen.height - aHeight ) / 2;
      var lWin = window.open( aUrl, aName, 'height=' + aHeight + ',width=' + aWidth + ',left=' + lLeft + ',top=' + lTop + ',toolbar=no,directories=no,status=no,menubar=no,scrollbars=' + ( aScroll ? 'yes' : 'no' ) + ',resizable=no,modal=' + ( aModal ? 'yes' : 'no' ) );
      try {
         lWin.focus();
      } catch ( e ) {
         customAlert( "Error", "Your browser seems to have blocked the popup chat window.<br><br>Please try turning off the popup blocker." );
      }
   }
}

// Javascript class used to do ajax field validation
function FieldValidator( aFieldId )
{
   var iThis = this;

   this.iFieldId = aFieldId;
   this.iField = document.getElementById( aFieldId );
   this.iOldValue = this.iField.value;
   this.iMsgTable = null;
   this.iJavaMethod = null;
   this.jsValidate = null;
   this.iExtraArgs = "";
   this.iSuccessMsg = null;
   this.iErrorMsg = null;
   
   // Initialize class
   this.init = function()
   {
      addWindowOnLoadEvent(
         function() { iThis.updateField( true ); }
      );
   
      this.iMsgTable = document.createElement( "table" );
      var lMsgRow = this.iMsgTable.insertRow( -1 );
      var lMsgCell = lMsgRow.insertCell( -1 );

      this.iField.insertAdjacentElement( "afterEnd", this.iMsgTable );
      
      this.iMsgTable.className = "inputFieldMsgTable";
      this.iMsgTable.cellSpacing = 1;
      this.iMsgTable.cellPadding = 1;
   };
   
   // Called whenever the field is updated
   this.updateField = function( aForce )
   {
      var lNewValue = this.iField.value;
      if ( lNewValue == null || lNewValue == "" ) {
         this.hideMsg();
      }
      else if ( aForce || this.iOldValue != lNewValue ) {
         if ( this.jsValidate == null ) {
            this.ajaxCall();
         } else {
            this.showMsg( this.jsValidate() );
         }
      }
      this.iOldValue = lNewValue;
   };

   // Ajax call
   this.ajaxCall = function() {
      eval( this.iJavaMethod + "( this.iField.value, " + this.iExtraArgs + "this.ajaxHandler )" );
   }
   
   // Ajax return handler
   this.ajaxHandler = function( aData )
   {
      iThis.showMsg( aData );
   };
   
   // Add onkeyup handler for input field to force refresh
   this.iField.onkeyup = function()
   {
      iThis.updateField( false );
   };

   // Add onblur handler for input field to force refresh
   this.iField.onblur = function()
   {
      iThis.updateField( false );
   };

   // Sets the name of the java method to do the validating
   this.setJavaMethod = function( aJavaMethod )
   {
      this.iJavaMethod = aJavaMethod;
      if ( arguments.length > 1 ) {
         for ( var i = 1; i < arguments.length; i++ ) {
            this.iExtraArgs += "\"" + arguments[i] + "\", ";
         }
      }
   }
   
   // Optionally sets a successful message if no errors
   this.setSuccessMessage = function( aMsg )
   {
      this.iSuccessMsg = aMsg;
   }
   
   // Shows a message
   this.showMsg = function( aMsg )
   {
      this.iErrorMsg = aMsg;
      var lMsg = aMsg == null ? this.iSuccessMsg : aMsg;

      // If the message is still null, then hide the table
      if ( lMsg == null || lMsg.length == 0 ) {
         this.hideMsg();
      }
      // Otherwise, show the table
      else {
         this.iMsgTable.getElementsByTagName("td")[0].innerHTML = lMsg;
         this.iMsgTable.style.display = "inline";
      }
   };
   
   // Hides the message table
   this.hideMsg = function()
   {
      this.iErrorMsg = null;
      this.iMsgTable.style.display = "none";
   };
   
   // Gets the current error message for this validator
   this.getErrorMsg = function()
   {
      return this.iErrorMsg;
   };
}

// Firefox implementation for the IE insertAdjacentElement method
if ( typeof HTMLElement != "undefined" && !HTMLElement.prototype.insertAdjacentElement ) { 
   HTMLElement.prototype.insertAdjacentElement = function( where, parsedNode ) 
   { 
      switch ( where ) { 
         case 'beforeBegin': 
            this.parentNode.insertBefore( parsedNode, this ) 
            break; 
         case 'afterBegin': 
            this.insertBefore( parsedNode, this.firstChild ); 
            break; 
         case 'beforeEnd': 
            this.appendChild( parsedNode ); 
            break; 
         case 'afterEnd': 
            if ( this.nextSibling ) {
               this.parentNode.insertBefore( parsedNode, this.nextSibling );
            } else { 
               this.parentNode.appendChild( parsedNode );
            } 
            break;
      }
   } 
}

// Executes a request to the given url
function createRequestGet( aUrl, aHandler )
{
   // If a new request was created, send it
   var lXMLRequest = getXmlRequest();
   if ( lXMLRequest != null ) {

      // Pass extra arguments
      var lArgs = new Array();
      lArgs[0] = lXMLRequest;

      // Add all extra parameters passed to this method over what was expected
      for ( var i = createRequestGet.length; i < arguments.length; i++ ) {
         lArgs.push( arguments[i] );
      }

      // Send the request
      aUrl += "&aTime=" + new Date().getTime(); 
      lXMLRequest.onreadystatechange = function( aEvt ) { processRequestChange( aHandler, lArgs ) };
      lXMLRequest.open( "GET", aUrl, true );
      lXMLRequest.setRequestHeader( "Content-Type", "text/html" );
      lXMLRequest.send( null );
   }
}

// Executes a request to the given url
function createRequestPost( aUrl, aParameters, aHandler )
{
   // If a new request was created, send it
   var lXMLRequest = getXmlRequest();
   if ( lXMLRequest != null ) {

      // Pass extra arguments
      var lArgs = new Array();
      lArgs[0] = lXMLRequest;

      // Add all extra parameters passed to this method over what was expected
      for ( var i = createRequestPost.length; i < arguments.length; i++ ) {
         lArgs.push( arguments[i] );
      }
      
      // Send the request
      lXMLRequest.onreadystatechange = function( aEvt ) { processRequestChange( aHandler, lArgs ) };
      lXMLRequest.open( "POST", aUrl, true );
      lXMLRequest.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
      lXMLRequest.setRequestHeader( "Content-length", aParameters == null ? 0 : aParameters.length );
      lXMLRequest.setRequestHeader( "Connection", "close" );
      lXMLRequest.send( aParameters );
   }
}

// Retrieves an xml request object
function getXmlRequest()
{
   // Initialize the request var to null
   var lXMLRequest = null;

   // Branch for native XMLHttpRequest object
   if ( window.XMLHttpRequest ) {
      try {
         lXMLRequest = new XMLHttpRequest();
      } catch ( lException ) {
         lXMLRequest = null;
      }
   }
   // Branch for IE/Windows ActiveX version
   else if ( window.ActiveXObject ) {
      try {
         lXMLRequest = new ActiveXObject( "Msxml2.XMLHTTP" );
      } catch ( lException ) {
         try {
            lXMLRequest = new ActiveXObject( "Microsoft.XMLHTTP" );
         } catch ( lException ) {
            lXMLRequest = null;
         }
      }
   }
   
   return lXMLRequest;
}

// Handler for when the request status changes
function processRequestChange( aHandler, aArgs ) {
   if ( aArgs[0].readyState == 4 ) {
      aHandler.call( this, aArgs );
   }
}

// Disables a submit button in a form when it's submitted
function disableSubmit( aSubmitId, aText )
{
   jQuery("#" + aSubmitId).attr("disabled", "true");
   if ( aText != null ) {
      jQuery(aSubmitId).val(aText);
   }
   return true;
}

// Disables a submit button in a form when it's submitted
function enableSubmit( aSubmitId, aText )
{
   jQuery("#" + aSubmitId).removeAttr("disabled");
   if ( aText != null ) {
      jQuery(aSubmitId).val(aText);
   }
   return true;
}

// Returns true if this is IE6
function isIE6()
{
   return navigator.userAgent.toLowerCase().indexOf('msie 6') != -1;
}

// Trim method for a string
String.prototype.trim = function() {
   return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""));
}

// Checks if a string starts with
String.prototype.startsWith = function(str) 
{return (this.match("^"+str)==str)}

// Check if a string ends with
String.prototype.endsWith = function(str) 
{return (this.match(str+"$")==str)}

// Checks for blank string
function isBlank( aString ) {
   return aString == null || aString.trim() == "";
}

// Check if string is a whole number(digits only). 
var isWholeNumber_re = /^\s*\d+\s*$/; 
function isWholeNumber( aString ) { 
   return String( aString ).search( isWholeNumber_re ) != -1 ;
}


// Class used to encode and decode strings
var Url = {

    // public method for url encoding
    encode : function (string) {
        return encodeURIComponent(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(decodeURIComponent(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
};

// Turns text to save html
function toSaveHtml( text ) {
   var textneu = text.replace(/&/g,"&amp;");
   textneu = textneu.replace(/</g,"&lt;");
   textneu = textneu.replace(/>/g,"&gt;");
   textneu = textneu.replace(/\r\n/g,"<br>");
   textneu = textneu.replace(/\n/g,"<br>");
   textneu = textneu.replace(/\r/g,"<br>");
   return (textneu);
}

function toast( aMessage ) {
   $(function(){
      var t = $.toaster({showTime:2000, centerX:true, centerY:true});
      t.toast(aMessage);
   });
}
