/**
 * Carousel generator
 * @version	0.1 
 */

var CarouselOptions = {
	callbackItem: null,
	container: "#slideClients",
	leftClass: ".preview",
	rightClass: ".next",
	itemWidth: 230,
	speed: 200
}

var Carousel = function(el, parent, options){
	//	Set options
	options = ( !options ) ? CarouselOptions : options;
		
	//------------	Private	------------
	/**
	 * @private
	 * Carousel DOM object
	 */
	var carousel = $(el);
	
	/**
	 * @private
	 * Carousel parent
	 */
	var suscriber = $(parent);
	
	/**
	 * @private
	 * Container
	 */
	var carouselContainer = carousel.find(options.container);
	
	
	/**
	 * Separator between items
	 */
	var horizontalGap = 0;
		
	/**
	 * Navigation arrows
	 */
	var leftArrow = carousel.find(options.leftClass);
	var rightArrow = carousel.find(options.rightClass);
	
	/**
	 * Carousel item width
	 */
	var item_width = options.itemWidth;
	
	/**
	 * Carousel speed
	 */
	var num_speed = options.speed;
	/**
	 * Carousel left position (scrolling)
	 */
	var num_currentPosition = 0;
	
	/**
	 * @private
	 * Current index
	 */
	var num_currentItem = 0;
	
	var num_totalItems = 0;
	
	var num_leftValue = 0;
	
	var num_carouselWidth = 0;
	
	
	//--------------------------------------
    //  Constructor
    //--------------------------------------
	var init = function(){
		buildCarousel();
	}();
	
	//--------------------------------------
	//  Public methods
	//--------------------------------------
	/**
	 * Get the current index for this carousel
	 * @returns	The current index
	 */
	function getCurrentItem(){
		return num_currentItem;
	};
	
	//--------------------------------------
	//  Private methods
	//--------------------------------------
	
	function buildCarousel(){
		num_totalItems = carouselContainer.find("li").length;
		num_leftValue = item_width * (-1);
		num_carouselWidth = carouselContainer.find("ul").width(num_totalItems * item_width);
		carousel.find("ul").css("left", 0);
		addEventListeners(true);
	}
	/**
	 * Add carousel event listeners
	 */
	function addEventListeners(enable){
		leftArrow.unbind("click");
		rightArrow.unbind("click");
		if(enable){
			leftArrow.click(left_clickHandler);
			rightArrow.click(right_clickHandler);
		}else{
			leftArrow.click(arrow_clickDisabledHandler);
			rightArrow.click(arrow_clickDisabledHandler);
		}	
	}
	
	
	//--------------------------------------
	//  Event Handlers
	//--------------------------------------
	/**
	 * Scroll carousel to left
	 * @param {Object} event
	 */
	function left_clickHandler(event){
		event.preventDefault();
		addEventListeners(false);
		carousel.find("ul").prepend(carousel.find("ul li").last());
		carousel.find("ul").css("left", num_leftValue);
		carousel.find("ul").animate({
			'left': parseInt(carousel.find("ul").css("left")) + item_width
			}, 200, function(){
				addEventListeners(true);
			});
	}
	
	/**
	 * Scroll carousel to right
	 * @param {Object} event
	 */
	function right_clickHandler(event){
		event.preventDefault();
		addEventListeners(false);
		carousel.find("ul").animate({
			'left': parseInt(carousel.find("ul").css("left")) - item_width
			}, 200, function(){
				carousel.find("ul").append(carousel.find("ul li").first());
				carousel.find("ul").css("left", 0);
				addEventListeners(true);
			});
	}
	
	function arrow_clickDisabledHandler(event){
		return false;
	}
	
	
	return {
		//getCurrentItem: getCurrentItem,
		//carouselDOM:function(){return carousel}
	};

};

/**
 * Slideshow
 * @version	0.1 
 */
var arr_backGroundColors = new Array("#014471", "#FFFFFF", "#FFFFFF","#53b7cf");

var SlideshowOptions = {
	containerClass: ".slideshowWrapper",
	autoplay: true,
	time: 500,
	delay: 2000,
	colors: arr_backGroundColors
}

var Slideshow = function(el, parent, options){
	//	Set options
	options = ( !options ) ? SlideshowOptions : options;
	
	//------------	Private	------------
	/**
	 * @private
	 * Slideshow DOM object
	 */
	var element = $(el);
	
	/**
	 * @private
	 * Slideshow parent
	 */
	var suscriber = $(parent);
	
	/**
	 * @private
	 * Container
	 */
	var wrapper = element.find(options.containerClass);
	
	/**
	 * @private
	 * Slideshow items
	 */
	var arr_items /* of object */ = ( options.arr_items ) ? options.arr_items : [];
	
	/**
	 * @private
	 * Slideshow data URL path
	 */
	var url = ( options.url ) ? options.url : '';
			
	/**
	 * @private
	 * Animation time
	 */
	var num_time = ( options.time ) ? options.time : 500;
	
	/**
	 * @private
	 * Delay time
	 */
	var num_delay = ( options.delay ) ? options.delay : 2000;
	
	
	var colors = ( options.colors ) ? options.colors : arr_backGroundColors;
	
	
	/**
	 * @private
	 * Slideshow total items
	 */
	var num_totalItems = 0;
	
		
	/**
	 * Slideshow left position (scrolling)
	 */
	var num_currentPosition = 0;
	
	var timer = null;
	
	/**
	 * @private
	 * Current index
	 */
	var num_currentItem = 0;
	
	/**
	 * @private
	 * Current banner
	 */
	var currentBanner;
	
	//--------------------------------------
    //  Constructor
    //--------------------------------------
	var init = function(){
		buildComponent();
	}();
	
	//--------------------------------------
	//  Public methods
	//--------------------------------------
	
	//--------------------------------------
	//  Private methods
	//--------------------------------------
	
	function buildComponent(){
		num_totalItems = wrapper.find("div[class!='txt']").length;
		currentBanner = wrapper.find("div[class!='txt']").first();
		addEventListeners();
		setTimeout(slideItems, num_delay);
		updateNavigation();
	}

	/**
	 * Add element event listeners
	 */
	function addEventListeners(){
		element.find('.selectedZone ul li a').click(numbers_clickHandler);
		
	}
	
	/**
	 * Update arrows
	 */
	function updateNavigation(){
		element.find('.selectedZone ul li a').removeClass("select");
		//	Set current slide number as selected
		$(element.find('.selectedZone ul li a').get(num_currentItem)).addClass("select");
	}
	
	/**
	 * Slide wrapper
	 */
	function slideItems(){
		wrapper.find("div[class!='txt']").addClass("bannerImage");
		currentBanner.fadeOut(300);
		num_currentItem += 1;
		if(num_currentItem < num_totalItems){
			currentBanner.next().fadeIn(300);
		}else{
			num_currentItem = 0;
			wrapper.find("div[class!='txt']").first().fadeIn(300);
		}
		currentBanner = wrapper.find("div[class!='txt']").eq(num_currentItem);
		changeBackgroundColor();
		updateNavigation();
		timer = setTimeout(slideItems, num_delay + num_time);
	}
	//--------------------------------------
	//  Event Handlers
	//--------------------------------------
	
	//------------	Item	------------
	/**
	 * Name or image clicked
	 * @param {Object} event
	 */
	function item_clickHandler(event){
		event.preventDefault();
		//	Fire Click Event
		suscriber.trigger(CustomEvent.ITEM_CLICK, event.data);
		//	Execute product detail functionallity
		if( typeof options.callbackItem == "function" ){
			options.callbackItem(arr_items[index]);
		}
		return false;
	}
	
	/**
	 * Icon link clicked
	 * @param {Object} event
	 */
	function numbers_clickHandler(event){
		event.preventDefault();
		num_currentItem = parseInt($(this).attr("title")) - 1;
		wrapper.find("div[class!='txt']").addClass("bannerImage");
		currentBanner.fadeOut(300);
		wrapper.find("div[class!='txt']").eq(num_currentItem).fadeIn(300);
		currentBanner = wrapper.find("div[class!='txt']").eq(num_currentItem);
		changeBackgroundColor();
		updateNavigation();
		//	Reset timer
		if (timer) {
			clearTimeout(timer);
			timer = setTimeout(slideItems, num_delay + num_time);
		}
		return false;
	}
	
	
	/**
	 * Change background banner color
	 */
	function changeBackgroundColor(){
		wrapper.animate({backgroundColor:colors[num_currentItem]}, 300);
	}
	
	
	return {
	};
};

$(document).ready(function(){
    Main.init();
});

var Main = {	
    //----------------------------------
    //  Constructor
    //----------------------------------
    /**
     * Initialize application
     */
    init: function(){
        Main.addEventListeners();
        if($("div.slideshowWrapper").length > 0)
        	Main.LoadSlideShow();
        if($("#slideClients").length > 0)
        	Main.LoadCarousel();
    },
    /**
     * Add event listeners to Main Application
     */
    addEventListeners: function(){
    	// Input text behavior
    	$("#search, #email").focusin(function(){
    		if (this.defValue == undefined) {
    			this.defValue = this.value;
    			this.value = ""; 
    		}else
    			this.value = this.userValue == undefined ? " " : this.userValue; 
    	}).change(function(){
    		this.userValue = this.value; 
    	}).focusout(function(){ 
    		if (this.userValue == undefined || this.userValue == "") {
    			this.value = this.defValue;
    		}else
    			this.value = this.userValue;
    	});
    	// Menu Divisions
    	$(".main ul li.hasSubmenu").each(function(){
        	$(this).mouseover(function(){
        		$(this).find(".separator").css({"visibility":"hidden"});
        		$(this).next().find(".separator").css({"visibility":"hidden"});
        	}).mouseout(function(){
        		$(this).find(".separator").css({"visibility":"visible"});
        		$(this).next().find(".separator").css({"visibility":"visible"});
        	});
        });
    	// Tabs (Events, Articles and Blogs)
    	$(".newsList > li > a").click(function(event){
    		event.preventDefault();
    		if(!$(this).hasClass("select")){
    			$(".newsList > li > a").removeClass("select");
    			$(this).addClass("select");
    			$(".newsList > li > ul").hide();
    			$(this).parent().find("ul").fadeIn('slow');
    		}	
    	});
    	//FAQ actions
    	$("#faq").find(".question").click(function(){
    		$(this).parent().find("p.answer").toggle();
    		//console.log($(this));
    	});
    	
    	//Popups (Login and register)
    	$(".btn_login, .btn_register").click(function(event){
    		event.preventDefault;
    		$("#overlay").fadeIn();
    		if($(this).hasClass("btn_login")){
    			$('#popupRegister').hide();
    			$("#popupLogin").fadeIn();
    		}else{
    			$('#popupLogin').hide();
    			$("#popupRegister").fadeIn();
    		}
    	});
    	
    	$(".close").click(function(event){
    		event.preventDefault;
			$(this).parent().hide();
			$("#overlay").hide();
		});
		
		
    },
    /**
     * Load Slideshow
     */
    LoadSlideShow: function(){
    	var arr_backGroundColors = new Array("#014471", "#FFFFFF", "#FFFFFF", "#53b7cf");
    	Slideshow(".bannerFirst", this, {
			containerClass: '.slideshowWrapper',
			time: 5000,
			animationSpeed: 300,
			colors: arr_backGroundColors
    	});
    },
    /**
     * Load Carousel
     */
    LoadCarousel: function(){
    	Carousel(".ourClients", this, {
    		container: "#slideClients",
    		leftClass: ".preview",
    		rightClass: ".next",
    		itemWidth: 230,
    		speed: 200
		});
    }
    
};

/*jslint browser: true */ /*global jQuery: true */

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

// TODO JsDoc

/**
 * Create a cookie with the given key and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String key The key of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given key.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String key The key of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function (key, value, options) {

    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};


(function($){
     $.fn.extend({
          center: function (options) {
               var options =  $.extend({ // Default values
                    inside:window, // element, center into window
                    transition: 0, // millisecond, transition time
                    minX:0, // pixel, minimum left element value
                    minY:0, // pixel, minimum top element value
                    vertical:true, // booleen, center vertical
                    withScrolling:true, // booleen, take care of element inside scrollTop when minX < 0 and window is small or when window is big
                    horizontal:true // booleen, center horizontal
               }, options);
               return this.each(function() {
                    var props = {position:'absolute'};
                    if (options.vertical) {
                         var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
                         if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
                         top = (top > options.minY ? top : options.minY);
                         $.extend(props, {top: top+'px'});
                    }
                    if (options.horizontal) {
                          var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
                          if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
                          left = (left > options.minX ? left : options.minX);
                          $.extend(props, {left: left+'px'});
                    }
                    if (options.transition > 0) $(this).animate(props, options.transition);
                    else $(this).css(props);
                    return $(this);
               });
          }
     });
})(jQuery);



// 2011 show/hide

function showDiv(iidee)
{
$('#'+iidee).show();
}

function hideDiv(iidee)
{
$('#'+iidee).hide();
}



/* IMAGE MANAGEMENT JAVASCRIPT */

function MM_swapImgRestore() {
  	var i, x, a = document.MM_sr;
  	for(i=0; a&&i < a.length&&(x=a[i])&&x.oSrc; i++) {
  		x.src=x.oSrc;
	}
}

function MM_preloadImages() {
  	var d = document;
	if(d.images){
		if(!d.MM_p) {
			d.MM_p=new Array();
		}
    	var i, j = d.MM_p.length, a = MM_preloadImages.arguments;
		for(i=0; i < a.length; i++) {
    		if (a[i].indexOf("#")!=0) {
				d.MM_p[j]=new Image;
				d.MM_p[j++].src=a[i];
			}
		}
	}
}

function MM_findObj(n, d) {
  	var p, i, x;
	if(!d) {
		d=document;
	}
	if((p=n.indexOf("?")) > 0&&parent.frames.length) {
    	d=parent.frames[n.substring(p+1)].document;
		n=n.substring(0,p);
	}
  	if(!(x=d[n])&&d.all) {
		x=d.all[n];
	}
	for (i=0; !x&&i<d.forms.length; i++) {
		x=d.forms[i][n];
	}
  	for(i=0; !x&&d.layers&&i<d.layers.length; i++) {
		x=MM_findObj(n,d.layers[i].document);
	}
	return x;
}

function MM_swapImage() {
  	var i, j = 0, x, a = MM_swapImage.arguments;
	document.MM_sr=new Array;
	for(i=0; i < (a.length-2); i+=3) {
   		if ((x=MM_findObj(a[i])) != null){
			document.MM_sr[j++]=x;
			if(!x.oSrc) {
				x.oSrc=x.src;
				x.src=a[i+2];
			}
		}
	}
}

function openPopup(theURL,winName,features)
{
    window.open(theURL,winName,features);
}

function openPreview(URLtoOpen,windowName,screenWidth, screenHeight) {
	var screenWidth;
	var screenHeight;

	if (navigator.appName == 'Microsoft Internet Explorer' && (navigator.platform.substring(0,3) == 'Win')) {
			var scw=screenWidth;
			var sch=screenHeight;
			var scl=(screen.width / 2) - (screenWidth / 2);
			var sct=(screen.height / 2) - (screenHeight / 2);
			window.open (URLtoOpen, windowName, "left=" + scl + ",top=" + sct + ",width=" + scw + ",height=" + sch + ',scrollbars=yes,status=no,resizable=yes');
		}
	else if (navigator.appName == 'Netscape' || navigator.platform == 'MacPPC') {
			var scw=screenWidth;
			var sch=screenHeight;
			var scl=(screen.width / 2) - (screenWidth / 2);
			var sct=(screen.height / 2) - (screenHeight / 2);
			window.open (URLtoOpen, windowName, "screenX=" + scl + ",screenY=" + sct + ",outerWidth=" + scw + ",outerHeight=" + sch + ',scrollbars=yes,status=no,resizable=yes');
		}
	else {
			var scw=screenWidth;
			var sch=screenHeight;
			var scl=(screen.width / 2) - (screenWidth / 2);
			var sct=(screen.height / 2) - (screenHeight / 2);
			window.open (URLtoOpen, windowName, "screenX=" + scl + ",screenY=" + sct + ",outerWidth=" + scw + ",outerHeight=" + sch + ',scrollbars=yes,status=no,resizable=yes');
		}
}


function openPopup(theURL,winName,features) {
	window.open(theURL,winName,features);
}

function show_msg(msg) { alert(msg); }

function validateForm() {
	missing_required = 0;

	for (i = 0; i < arguments.length; i++) {
		if(arguments[i] == '') {
			missing_required = 1;
		}
	}

	if(missing_required) {
		alert("A required form field is missing.");
		return false;
	} else {
		return true;
	}
}

function expCustomLink(myURL) {
	location.href = myURL;
}

function setStatus(message)
{
	window.status = message;
}

function setUrl(path)
{
	document.location.href = path;
}

var screenWidth;
var screenHeight;

function expArticleLink(sectionId, articleId) {

	location.href = '/index.php?section_id=' + sectionId + '&section_copy_id=' + articleId;
}

function expPopupWindow(url, widthVal, heightVal, resizableVal, scrollbarsVal, toolbarVal, locationVal, directoriesVal, statusVal, menubarVal, copyHistoryVal) {

	var attributes = "width="  	 	 + widthVal       +
				 	 ",height=" 	 + heightVal      +
				 	 ",resizable="  + resizableVal  +
				 	 ",scrollbars="  + scrollbarsVal  +
				 	 ",toolbar=" 	 + toolbarVal 	  +
				 	 ",location=" 	 + locationVal 	  +
				 	 ",directories=" + directoriesVal +
				 	 ",status=" 	 + statusVal 	  +
				 	 ",menubar=" 	 + menubarVal 	  +
				 	 ",copyhistory=" + copyHistoryVal;

	window.open(url, 'WindowName', attributes);
}

<!--
// callback pool needs global scope
var jsrsContextPoolSize = 0;
var jsrsContextMaxPool = 10;
var jsrsContextPool = new Array();
var jsrsBrowser = jsrsBrowserSniff();
var jsrsPOST = true;
var containerName;

// constructor for context object
function jsrsContextObj( contextID ){
  
  // properties
  this.id = contextID;
  this.busy = true;
  this.callback = null;
  this.container = contextCreateContainer( contextID );
  
  // methods
  this.GET = contextGET;
  this.POST = contextPOST;
  this.getPayload = contextGetPayload;
  this.setVisibility = contextSetVisibility;
}

//  method functions are not privately scoped 
//  because Netscape's debugger chokes on private functions
function contextCreateContainer( containerName ){
  // creates hidden container to receive server data 
  var container;
  switch( jsrsBrowser ) {
    case 'NS':
      container = new Layer(100);
      container.name = containerName;
      container.visibility = 'hidden';
      container.clip.width = 100;
      container.clip.height = 100;
      break;
    
    case 'IE':
      document.body.insertAdjacentHTML( "afterBegin", '<span id="SPAN' + containerName + '"></span>' );
      var span = document.all( "SPAN" + containerName );
      var html = '<iframe name="' + containerName + '" src="" charset="iso-8859-1"></iframe>';
      span.innerHTML = html;
      span.style.display = 'none';
      container = window.frames[ containerName ];
      break;
      
    case 'MOZ':  
      var span = document.createElement('SPAN');
      span.id = "SPAN" + containerName;
      document.body.appendChild( span );
      var iframe = document.createElement('IFRAME');
      iframe.name = containerName;
      iframe.id = containerName;
      span.appendChild( iframe );
      container = iframe;
      break;

    case 'OPR':  
      var span = document.createElement('SPAN');
      span.id = "SPAN" + containerName;
      document.body.appendChild( span );
      var iframe = document.createElement('IFRAME');
      iframe.name = containerName;
      iframe.id = containerName;
      span.appendChild( iframe );
      container = iframe;
      break;
  }
  return container;
}

function contextPOST( rsPage, func, parms ){
  var d = new Date();
  var unique = d.getTime() + '' + Math.floor(1000 * Math.random());
  var doc = (jsrsBrowser == "IE" ) ? this.container.document : this.container.contentDocument;
  
doc.open();
  doc.write('<html><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></head><body>');
  doc.write('<form accept-charset="iso-8859-1" name="jsrsForm" method="post" target="" ');
  doc.write(' action="' + rsPage + '&U=' + unique + '">');
  doc.write('<input type="hidden" name="C" value="' + this.id + '">');

  // func and parms are optional
  if (func != null){
  doc.write('<input type="hidden" name="F" value="' + func + '">');

    if (parms != null){
      if (typeof(parms) == "string"){
        // single parameter
        doc.write( '<input type="hidden" name="P0" '
                 + 'value="[' + jsrsEscapeQQ(parms) + ']">');
      } else {
        // assume parms is array of strings
        for( var i=0; i < parms.length; i++ ){
          doc.write( '<input type="hidden" name="P' + i + '" '
                   + 'value="[' + jsrsEscapeQQ(parms[i]) + ']">');
        }
      } // parm type
    } // parms
  } // func

  doc.write('</form></body></html>');
  doc.close();
  doc.forms['jsrsForm'].submit();

}

function contextGET( rsPage, func, parms ){

  // build URL to call
  var URL = rsPage;

  // always send context
  URL += "?C=" + this.id;

  // func and parms are optional
  if (func != null){
    URL += "&F=" + escape(func);

    if (parms != null){
      if (typeof(parms) == "string"){
        // single parameter
        URL += "&P0=[" + escape(parms+'') + "]";
      } else {
        // assume parms is array of strings
        for( var i=0; i < parms.length; i++ ){
          URL += "&P" + i + "=[" + escape(parms[i]+'') + "]";
        }
      } // parm type
    } // parms
  } // func

  // unique string to defeat cache
  var d = new Date();
  URL += "&U=" + d.getTime();
 
  // make the call
  switch( jsrsBrowser ) {
    case 'NS':
      this.container.src = URL;
      break;
    case 'IE':
      this.container.document.location.replace(URL);
      break;
    case 'MOZ':
      this.container.src = '';
      this.container.src = URL; 
      break;
    case 'OPR':
      this.container.src = '';
      this.container.src = URL; 
      break;
  }  
  
}

function contextGetPayload(){
  switch( jsrsBrowser ) {
    case 'NS':
      return this.container.document.forms['jsrs_Form'].elements['jsrs_Payload'].value;
    case 'IE':
      return this.container.document.forms['jsrs_Form']['jsrs_Payload'].value;
    case 'MOZ':
      return window.frames[this.container.name].document.forms['jsrs_Form']['jsrs_Payload'].value; 
    case 'OPR':
      var textElement = window.frames[this.container.name].document.getElementById("jsrs_Payload");
      return textElement.value;
  }  
}

function contextSetVisibility( vis ){
  switch( jsrsBrowser ) {
    case 'NS':
      this.container.visibility = (vis)? 'show' : 'hidden';
      break;
    case 'IE':
      document.all("SPAN" + this.id ).style.display = (vis)? '' : 'none';
      break;
    case 'MOZ':
      document.getElementById("SPAN" + this.id).style.visibility = (vis)? '' : 'hidden';
    case 'OPR':
      document.getElementById("SPAN" + this.id).style.visibility = (vis)? '' : 'hidden';
      this.container.width = (vis)? 250 : 0;
      this.container.height = (vis)? 100 : 0;
      break;
  }  
}

// end of context constructor

function jsrsGetContextID(){
  var contextObj;
  for (var i = 1; i <= jsrsContextPoolSize; i++){
    contextObj = jsrsContextPool[ 'jsrs' + i ];
    if ( !contextObj.busy ){
      contextObj.busy = true;      
      return contextObj.id;
    }
  }
  // if we got here, there are no existing free contexts
  if ( jsrsContextPoolSize <= jsrsContextMaxPool ){
    // create new context
    var contextID = "jsrs" + (jsrsContextPoolSize + 1);
    jsrsContextPool[ contextID ] = new jsrsContextObj( contextID );
    jsrsContextPoolSize++;
    return contextID;
  } else {
    alert( "jsrs Error:  context pool full" );
    return null;
  }
}

function jsrsExecute( rspage, callback, func, parms, visibility ){
  // call a server routine from client code
  //
  // rspage      - href to asp file
  // callback    - function to call on return 
  //               or null if no return needed
  //               (passes returned string to callback)
  // func        - sub or function name  to call
  // parm        - string parameter to function
  //               or array of string parameters if more than one
  // visibility  - optional boolean to make container visible for debugging

  // get context
  var contextObj = jsrsContextPool[ jsrsGetContextID() ];
  contextObj.callback = callback;

  var vis = (visibility == null)? false : visibility;
  contextObj.setVisibility( vis );

  if ( jsrsPOST && ((jsrsBrowser == 'IE') || (jsrsBrowser == 'MOZ'))){
    contextObj.POST( rspage, func, parms );
  } else {
    contextObj.GET( rspage, func, parms );
  }
  
  return contextObj.id;
}

function jsrsLoaded( contextID ){
  // get context object and invoke callback
  var contextObj = jsrsContextPool[ contextID ];
  if( contextObj.callback != null){
    contextObj.callback( jsrsUnescape( contextObj.getPayload() ), contextID );
  }
  // clean up and return context to pool
  contextObj.callback = null;
  contextObj.busy = false;
}

function jsrsError( contextID, str ){
  alert( unescape(str) );
  jsrsContextPool[ contextID ].busy = false
}

function jsrsEscapeQQ( thing ){
  return thing.replace(/'"'/g, '\\"');
}

function jsrsUnescape( str ){
  // payload has slashes escaped with whacks
  return str.replace( /\\\//g, "/" );
}

function jsrsBrowserSniff(){
if (document.layers) { return "NS"; }
if (document.all) {
		// But is it really IE?
		// convert all characters to lowercase to simplify testing
		var agt=navigator.userAgent.toLowerCase();
		var is_opera = (agt.indexOf("opera") != -1);
		if(is_opera) {
			return "OPR";
		} else {
			return "IE";
		}
  }
  if (document.getElementById) return "MOZ";
  return "OTHER";
}

function jsrsArrayFromString( s, delim ){
  // rebuild an array returned from server as string
  // optional delimiter defaults to ~
  var d = (delim == null)? '~' : delim;
  return s.split(d);
}

function jsrsDebugInfo(){
  // use for debugging by attaching to f1 (works with IE)
  // with onHelp = "return jsrsDebugInfo();" in the body tag
  var doc = window.open().document;
  doc.open;
  doc.write( 'Pool Size: ' + jsrsContextPoolSize + '<br><font face="arial" size="2"><b>' );
  for( var i in jsrsContextPool ){
    var contextObj = jsrsContextPool[i];
    doc.write( '<hr>' + contextObj.id + ' : ' + (contextObj.busy ? 'busy' : 'available') + '<br>');
    doc.write( contextObj.container.document.location.pathname + '<br>');
    doc.write( contextObj.container.document.location.search + '<br>');
    doc.write( '<table border="1"><tr><td>' + contextObj.container.document.body.innerHTML + '</td></tr></table>' );
  }
  doc.write('</table>');
  doc.close();
  return false;
}
//-->

