/*-------------------*/
/* Shared Javascript */
/*-------------------*/

/* these javascript functions and features are used on
   enough pages that it makes sense to include the code
   on every page on the site */
   
// global page element
// reference repository
rpr__pg = new Object();   



/*-----------------*/
/* Page Components */
/*-----------------*/   

jQuery(document).ready(function($) {
    
  // on all similar page elements use 
  // javascript to center text vertically
  // as it yields the best results across
  // all broswers for alignment consistency
  var el = $('.rpr-menu div.button h1, '+
             'div#rpr-header.members-area div.logout div, '+
             'div#rpr-header.admin-area div.logout div');
  el.each(function (i, el) {
    
    // on each element we must calculate text position
    var mrg = ($(el).parent().height() - $(el).height()) / 2;
    if ((rpr__client.OS == 'Mac') && (rpr__client.browser == 'Safari')) mrg += 1;
    $(el).css('marginTop', mrg);    
  });
  
  // use function to align button
  // labels on all visible buttons
  rpr__align_rounded_button_labels();
  
  // as before automatically center the footer text
  var div = $('div#rpr-footer ul.bar li.text div');
  var mrg = (div.parent().height() - div.height()) / 2;
  if ((rpr__client.OS == 'Mac') && (rpr__client.browser == 'Safari')) mrg += 1;
  div.css('marginTop', mrg);
  
  // when present automatically center arrow labels
  var div = $('div.rpr-step-arrows .arrow div.text');
  div.each(function (i, el) {
    
    // on each element we must calculate the label position
    var mrg = ($(el).parent().height() - $(el).height()) / 2;
    if ((rpr__client.OS == 'Mac') && (rpr__client.browser == 'Safari')) mrg += 1;
    $(el).css('marginTop', mrg);
  });
  
  // since ie6 does not
  // support css hover
  // on all elements
  if (rpr__is_ie6())
  {
    // allow the menus to be opened by clicking
    // the button add using a specialized class
    $('.rpr-menu div.button').click(function(e) {
      e.preventDefault();
      var $ = jQuery;
      var m = $(this).parents('.rpr-menu');
      if (m.hasClass('hover')) $('.rpr-menu').removeClass('hover'); 
      else {
        $('.rpr-menu').removeClass('hover'); 
        m.addClass('hover');
      }
    });
  }
  
  /*------------------------*/
  /* Default Form Behaviors */
  /*------------------------*/
  
  // enable the stylized buttons to submit their forms when they
  // are clicked as well as appropriately classed html links too
  var will_submit = $('.rpr-rounded-button.rpr-submit, a.rpr-submit');
  will_submit.click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    
    // automatically submit the 
    // form which encloses the button
    var f = $(this).parents('form');
    if (f.get(0)) f.get(0).submit();
  });
  
  // allow the enter key to submit when form classed
  $('form.rpr-enter-submits').keypress(function(e) {
    if (e.which == 13) this.submit();
  });
  
  /*--------------------------------*/
  /* Automaic Disabling of Elements */
  /*--------------------------------*/
  
  // allow properly tagged links to be
  // easily disabled wherever they appear
  $('a.rpr-disabled').click(function(e) {
    e.preventDefault();
    e.stopPropagation();
  });
  
  /*--------------------------------*/
  /* Default Brief Profile Behavior */
  /*--------------------------------*/
  
  // enable the make contact button which is displayed on full profile to toggle boxed area to show contact
  $('div.rpr-member-profile div.brief.bottom div.button .rpr-rounded-button.make-contact').click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    var btns = $(this).parent();
    btns.find('.rpr-rounded-button.make-contact').addClass('rpr-hidden');
    btns.find('.rpr-rounded-button.view-profile').removeClass('rpr-hidden');
    var box = $(this).parents('div.rpr-member-profile').find('div.brief.middle div.information');
    box.find('div.highlights').hide();
    box.find('div.contact-details').show();
    rpr__align_rounded_button_labels();
  });
  
  // enable the view profile button which is displayed on full profile to toggle back to main profile highlights
  $('div.rpr-member-profile div.brief.bottom div.button .rpr-rounded-button.view-profile').click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    var btns = $(this).parent();
    btns.find('.rpr-rounded-button.make-contact').removeClass('rpr-hidden');
    btns.find('.rpr-rounded-button.view-profile').addClass('rpr-hidden');
    var box = $(this).parents('div.rpr-member-profile').find('div.brief.middle div.information');
    box.find('div.highlights').show();
    box.find('div.contact-details').hide();
    rpr__align_rounded_button_labels();
  });
  
  // enable the view full profile button to slide out the rest of the profile contents into view
  $('div.rpr-member-profile div.brief.bottom div.button .rpr-rounded-button.view-full').click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    var p = $(this).parents('div.rpr-member-profile');
    var f = p.find('div.full');
    f.hide();
    p.addClass('full').removeClass('brief');
    f.slideDown('slow');
    rpr__align_rounded_button_labels();
  });
  
  // enable the small close link to collapse back to brief profile
  $('div.rpr-member-profile div.full div.close a').click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    var p = $(this).parents('div.rpr-member-profile');
    var f = p.find('div.full');
    f.slideUp('slow', function() { 
      
      // when the full profile has been retracted 
      // show the highlights if contact details shown
      var btns = p.find('div.brief.bottom div.button');
      btns.find('.rpr-rounded-button.make-contact').removeClass('rpr-hidden');
      btns.find('.rpr-rounded-button.view-profile').addClass('rpr-hidden');
      var box = p.find('div.brief.middle div.information');
      box.find('div.highlights').show();
      box.find('div.contact-details').hide();
      p.addClass('brief').removeClass('full'); 
      rpr__align_rounded_button_labels(); 
    });
  });
  
  /*-----------------------------*/
  /* View More Feedback Lightbox */
  /*-----------------------------*/
  
  $('div.rpr-member-profile div.feedback .rpr-rounded-button.view-more-feedback').click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    
    // reference the container
    var p = $(this).parent();
    
    // make a clone of the basic frame of the lightbox feedback content
    var fb = p.find('div.rpr-member-profile-lightbox-feedback').clone();
    fb.removeClass('rpr-hidden');
    
    // add the proper closing behavior to the cloned link
    fb.find('.rpr-lightbox-closer').click(function(e) {
      e.preventDefault(); rpr__lightbox.close(); });
    
    // open the lightbox with
    // the html and proceed to
    // load the feedback html
    rpr__lightbox.open(fb);
    
    // extract important strings from the page in order to request
    // the feedback properly and display an error in case of error
    var admin_view = (p.find('span.admin-view').text() == 'YES');
    var member_id = parseInt(p.find('span.member-id').text());
    var server_url = p.find('span.path-to-server').text();
    rpr__lightbox.window.data('ajax-error', p.find('span.ajax-error').text());
    
    // define a function which will handle
    // both success and failure of our post
    var complete = function(data, status) {
      
      // obtain a reference to the content area of the feedback lightbox window into to insert the response
      var div = rpr__lightbox.window.find('div.rpr-member-profile-lightbox-feedback div.feedback-content');
      
      // handle errors by displaying a simple string in the content area based on language
      if (status != 'success') div.empty().append(rpr__lightbox.window.data('ajax-error'));
      else div.empty().append(data);
    };
    
    // compose an execute the
    // ajax request for feedback
    $.ajax({ url: server_url,
             type: "POST",
             cache: false,
             data: { action: 'retrieve_feedback',
                     member: member_id,
                     admin_view: (admin_view ? 'YES' : 'NO') },
             dataType: 'html',
             success: complete,
             error: complete });
  });
  
  /*------------------------------------*/
  /* Changing Language Warning Lightbox */
  /*------------------------------------*/
  
  // encapsulate the process of display a language warning for a target language with a continue to a destination address
  $('#rpr-content .rpr-news-panel .rpr-flag-panel').data('changing_language_warning', function(name, continue_to_href) {
    var p = $('#rpr-content .rpr-news-panel');
    
    // make a clone of the basic lightbox content we will display unhide it and add close behaviors
    var lb = p.find('div.rpr-changing-language-warning-lightbox').clone().removeClass('rpr-hidden');
    
    // replace the language marker with full name within the title and contents of the warning    
    lb.find('div.contents').html(lb.find('div.contents').html().replace(/%%LANGUAGE%%/g, name));
    lb.find('div.title').html(lb.find('div.title').html().replace(/%%LANGUAGE%%/g, name));
    
    // add close behaviors to the updated html content in order to preserve the event handlers
    lb.find('.rpr-lightbox-closer').click(function(e) { e.preventDefault(); rpr__lightbox.close(); });
    lb.find('a.continue-with-change').attr('href', continue_to_href);
    
    // open the lightbox with
    // the html approval message
    rpr__lightbox.open(lb);
  });
  
  // for the flag panel links we can extract the parameters then call warning
  $('#rpr-content .rpr-news-panel .rpr-flag-panel a').click(function(e) {
    var p = $(this).parents('.rpr-news-panel');
    var continue_to_href = $(this).attr('href');
    var cur = p.find('.rpr-flag-panel span.current-language').text();
    var name = $(this).find('span.name').text();
    var code = $(this).find('span.code').text();
    if (cur == code || $(this).hasClass('no-warning')) return true;
    e.preventDefault();
    e.stopPropagation();
    if ($(this).hasClass('rpr-disabled')) return;
    
    // use the encapsulated function which is stored with the flag panel to present warning
    p.find('.rpr-flag-panel').data('changing_language_warning')(name, continue_to_href);
  });
  
  /*--------------------------------------------------------------------*/
  /* Administration -- Synchronization of Select Member Drop-Down Menus */
  /*--------------------------------------------------------------------*/
  
  $('div#rpr-content.admin-area div.rpr-select-user select').change(function(e) {
    var v = $(this).val();
    $(this).parents('div.rpr-select-user').find('select').val(v);
  });
  
  /*----------------------------------------------------------------------*/
  /* Administration -- Inclusion/Exclusion of Past Rounds From Drop-Downs */
  /*----------------------------------------------------------------------*/
  
  // in certain cases it is necessary to add this functionality after ready
  rpr__pg.rpr__enable_include_exclude_rounds_in_the_past_links = function() {
    
    // enable the links with speical class designations to show and hide
    // all rounds which are considered in the past, usually for drop downs
    $('div#rpr-content.admin-area a.rpr-past-rounds').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      if ($(this).hasClass('include'))
      {
        $(this).hide();
        $('a.rpr-past-rounds.exclude').show();
        $('.rpr-round-in-the-past').show();
      }
      else if ($(this).hasClass('exclude'))
      {
        $(this).hide();
        $('a.rpr-past-rounds.include').show();
        $('.rpr-round-in-the-past').hide();
      }
    });
  };
  
  // in most cases we can enable these links as soon as 
  // the page is loaded so call the function to do this
  rpr__pg.rpr__enable_include_exclude_rounds_in_the_past_links();
  
  /*------------------------------------------------------------------------------*/
  /* Member's Area/Administration -- Enable "More" Instructions Links to Function */
  /*------------------------------------------------------------------------------*/
  
  // enable links to be present which will show expanded page instructions
  $('div#rpr-content a.rpr-show-more-instructions').click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    $(this).parent().find('.more').show();
    $(this).hide();
  });
  
  /*------------------------------------------------------------------------------------------------*/
  /* Member's Area/Administration -- Enable Member's Profile Form "Reveal Other" Links to Function  */
  /*------------------------------------------------------------------------------------------------*/
  
  // allow the reveal other fields link to show the other text boxes on form
  var a = $('table.rpr-form.member-profile td.input p.reveal-others a');
  a.each(function(i, el) {
    if (!($(el).parent().hasClass('rpr-hidden'))) $(el).click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      $(this).parents('td.input').children('table.other').removeClass('rpr-hidden');
      $(this).parent().hide();
    });  
    
    // we will use the hidden reveal link to indicate we must show the other table
    else $(el).parents('td.input').children('table.other').removeClass('rpr-hidden');
  });
  
  /***********************************************************/
  /* Sliding Panels w/Slide Toggling Links (Used Throughout) */
  /***********************************************************/
  
  // we have established a convention whereby a toggler and panel contained in the properly
  // classed element will be automatically linked together to allow the panel to toggle slide
  $('.rpr-sliding-panel-container').find('.rpr-sliding-panel-toggler').click(function(e) {
    e.preventDefault();
    $(this).parents('.rpr-sliding-panel-container').find('.rpr-sliding-panel').slideToggle();
  });
  
});

function rpr__align_rounded_button_labels(container)
{
  // encapsulate this process as it
  // needs to be used after the page
  // is loaded in certain circumstances
  var $ = jQuery;
  
  // when no localized container is provided
  // default to the entire document itself
  if (!container) container = $(document);
  
  // use javascript to center text on all stylized buttons
  var lbl = container.find('.rpr-rounded-button .label div');
  lbl.each(function (i, el) {
    
    // on each element we must calculate the label position
    var mrg = ($(el).parent().height() - $(el).height()) / 2;
    if ((rpr__client.OS == 'Mac') && (rpr__client.browser == 'Firefox')) 
      if ($(el).parents('.rpr-newsletter-signup-panel').size()) mrg -= 1;
      else if ($(el).parents('.rpr-round-banner').size()) mrg -= 1;
    $(el).css('marginTop', mrg);
  });  
}










  
/*----------------------*/
/* Browser/OS Detection */
/*----------------------*/

// this code was adapted from a 
// free script found on the web

var rpr__client = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.userAgent,
			subString: "iPhone",
			identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

rpr__client.init();

/* IE6 Detection */

function rpr__is_ie6()
{
  // this method is independent of jquery and borrowed from the
  // sleight png transparency script to detect explorer versions
  var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
  var isIE6 = (rslt != null && Number(rslt[1]) < 7.0);
  return isIE6;
}  





/*-----------------*/
/* Custom Lightbox */
/*-----------------*/

// define the lightbox feature
// in an object and initialize
var rpr__lightbox = new Object();
rpr__lightbox.visible = false;

rpr__lightbox.open = function(contents)
{
  /* jQuery */
  (function($) 
  { 
    if (!rpr__lightbox.overlay) return;
    if (!rpr__lightbox.window) return;
    
    // when the contents to show have
    // been provided the window shall
    // wrap to fit contents precisely
    if (contents instanceof jQuery)
    {
      rpr__lightbox.window.css('width', contents.css('width'));
      rpr__lightbox.window.css('height', contents.css('height'));
      rpr__lightbox.window.empty().append(contents);
    }
    
    // prepare lightbox for display
    // and set css style to show
    rpr__lightbox.visible = true;
    rpr__lightbox.reposition();
    rpr__lightbox.overlay.css('display', 'block');
    rpr__lightbox.window.css('display', 'block');
  })(jQuery);
}

rpr__lightbox.close = function()
{
  /* jQuery */
  (function($) 
  {     
    if (!rpr__lightbox.overlay) return;
    if (!rpr__lightbox.window) return;
    
    // simply hide the elements and set flag
    rpr__lightbox.window.css('display', 'none');
    rpr__lightbox.overlay.css('display', 'none');
    rpr__lightbox.visible = false;
  })(jQuery);
}

rpr__lightbox.reposition = function()
{
  /* jQuery */
  (function($) 
  { 
    // only perform the repositioning
    // when visible flag is set to save
    // processing when lightbox is hidden
    if (!rpr__lightbox.visible) return;
    if (!rpr__lightbox.overlay) return;
    if (!rpr__lightbox.window) return;
    
    // determine the scrollable width and height of the window which may be based on two factors    
    //var width = $(window).width() < $(document).width() ? $(document).width() : $(window).width();
    //var height = $(window).height() < $(document).height() ? $(document).height() : $(window).height();
    
    rpr__lightbox.overlay.width($(window).width());
    rpr__lightbox.overlay.height($(window).height());
    rpr__lightbox.overlay.css('top', $(window).scrollTop());
    rpr__lightbox.overlay.css('left', $(window).scrollLeft());
    
    // center the content window within the current browswer window by computing proper offsets
    var top = $(window).scrollTop() + ( ($(window).height() - rpr__lightbox.window.height()) / 2 );
    var left = $(window).scrollLeft() + ( ($(window).width() - rpr__lightbox.window.width()) / 2 );
    rpr__lightbox.window.css('top', top);
    rpr__lightbox.window.css('left', left);
  })(jQuery);
};

/*--------------------------------*/
/* Custom Lightbox Initialization */
/*--------------------------------*/

jQuery(document).ready(function($) {
  
  // elements which compose the mechanics of the lightbox are added in all cases and ready to use
  $('body').append('<div id="rpr-lightbox-overlay"></div><div id="rpr-lightbox-window"></div>');
  
  // now set global references to the main elements
  rpr__lightbox.overlay = $('div#rpr-lightbox-overlay');
  rpr__lightbox.window = $('div#rpr-lightbox-window');
  
  // set opacity and closeability of overlay
  rpr__lightbox.overlay.css('opacity', 0.6);
  rpr__lightbox.overlay.click(rpr__lightbox.close);
  
  // now set all document elements so designated to 
  // properly close the lightbox when they are clicked
  $('.rpr-lightbox-closer').click(function(e) {
     e.preventDefault(); rpr__lightbox.close(); });
  
  // ensure lightbox adjusts as window changes
  $(window).resize(rpr__lightbox.reposition);
  $(window).scroll(rpr__lightbox.reposition);  
});


/*------------------*/
/* Email Validation */
/*------------------*/

function rpr__is_valid_email(str) {
// These comments use the following terms from RFC2822:
// local-part, domain, domain-literal and dot-atom.
// Does the address contain a local-part followed an @ followed by a domain?
// Note the use of lastIndexOf to find the last @ in the address
// since a valid email address may have a quoted @ in the local-part.
// Does the domain name have at least two parts, i.e. at least one dot,
// after the @? If not, is it a domain-literal?
// This will accept some invalid email addresses
// BUT it doesn't reject valid ones.
var atSym = str.lastIndexOf("@");
if (atSym < 1) { return false; } // no local-part
if (atSym == str.length - 1) { return false; } // no domain
if (atSym > 64) { return false; } // there may only be 64 octets in the local-part
if (str.length - atSym > 255) { return false; } // there may only be 255 octets in the domain
// Is the domain plausible?
var lastDot = str.lastIndexOf(".");
// Check if it is a dot-atom such as example.com
if (lastDot > atSym + 1 && lastDot < str.length - 1) { return true; }
// Check if could be a domain-literal.
if (str.charAt(atSym + 1) == '[' && str.charAt(str.length - 1) == ']') { return true; }
return false;
}