/*
 * End jQuery Timer Plugin
 */

jQuery.fn.outerHtml = function()
{
  return $('<div>').append( this.eq(0).clone() ).html();
};

function MessageScroller(elementId, messages, fadeDelay, pauseDelay)
{
  this.messageElementId = elementId;
  this.messages = messages; //message array content
  this.messageId = 0;
  this.innerElement;
  this.fadeDelay = 2000;
  this.pauseDelay = 4000;
  
  if (fadeDelay)
    this.fadeDelay = fadeDelay;
	
  if (pauseDelay)
	    this.pauseDelay = pauseDelay;
  
  var instance = this;
  
  instance.initialize();
}

MessageScroller.prototype.initialize=function()
{
  var messageElement = $("#" + this.messageElementId);

  var tableElement = $(document.createElement("table"));

  var trElement = $(document.createElement("tr"));
  tableElement.html(trElement);

  var tdElement = $(document.createElement("td"));
  tdElement.html(this.messages[this.messageId])
  trElement.html(tdElement);

  this.innerElement = tableElement;
  
  messageElement.html(tableElement);

  var instance = this;

  setTimeout(function(){instance.nextMessage()}, instance.pauseDelay);
}

MessageScroller.prototype.nextMessage=function()
{
  var instance = this;

  instance.innerElement.fadeOut(instance.fadeDelay, function()
  {
	instance.messageId = ((instance.messageId + 1) % instance.messages.length);
    $(instance.innerElement).find("td").html(instance.messages[instance.messageId])
  });
  
  instance.innerElement.fadeIn(instance.fadeDelay, function()
  {
    setTimeout(function(){instance.nextMessage()}, instance.pauseDelay);
  });
}

jQuery.fn.center = function(params)
{
  var options = {
    vertical: true,
	horizontal: true
  }

  op = jQuery.extend(options, params);

  return this.each(function()
  {
	//initializing variables
	var $self = jQuery(this);

	//get the dimensions using dimensions plugin
	var width = $self.width();
	var height = $self.height();
	
	//get the paddings
	var paddingTop = parseInt($self.css("padding-top"));
	var paddingBottom = parseInt($self.css("padding-bottom"));
	
	//get the borders
	var borderTop = parseInt($self.css("border-top-width"));
	var borderBottom = parseInt($self.css("border-bottom-width"));
	
	borderTop = (isNaN(borderTop) ? 0 : borderTop);
	borderBottom = (isNaN(borderBottom) ? 0 : borderBottom);
	
	//get the media of padding and borders
	var mediaBorder = (borderTop + borderBottom) / 2;
	var mediaPadding = (paddingTop + paddingBottom) / 2;

	mediaBorder = (isNaN(mediaBorder) ? 0 : mediaBorder);
	mediaPadding = (isNaN(mediaPadding) ? 0 : mediaPadding);

	//get the type of positioning
	var positionType = $self.parent().css("position");
	// get the half minus of width and height
	var halfWidth = (width/2)*(-1);
	var halfHeight = ((height/2)*(-1))-mediaPadding-mediaBorder;
	// initializing the css properties
	var cssProp = {
//		position: 'fixed'
	};
	
	var top = ($(window).height() / 2) + halfHeight;
	var left = ($(window).width() / 2) + halfWidth;

	top = (top < 0 ? 0 : top);
	left = (left < 0 ? 0 : left);

//	var buf = "";
//	buf += "width = " + width + "\n";
//	buf += "height = " + height + "\n";
//	buf += "paddingTop = " + paddingTop + "\n";
//	buf += "paddingBottom = " + paddingBottom + "\n";
//	buf += "borderTop = " + borderTop + "\n";
//	buf += "borderBottom = " + borderBottom + "\n";
//	buf += "mediaBorder = " + mediaBorder + "\n";
//	buf += "mediaPadding = " + mediaPadding + "\n";
//	buf += "positionType = " + positionType + "\n";
//	buf += "halfWidth = " + halfWidth + "\n";
//	buf += "halfHeight = " + halfHeight + "\n";
//	buf += "top = " + top + "\n";
//	buf += "left = " + left + "\n";
//	buf += "$(window).height() = " + $(window).height() + "\n";
//	buf += "$(window).width() = " + $(window).width() + "\n";
//	buf += "op.vertical = " + op.vertical + "\n";
//	buf += "op.horizontal = " + op.horizontal + "\n";
//	
//	alert(buf);
	
	if (op.vertical)
	{
		cssProp.height = height;
		cssProp.top = top;
	}
	
	if (op.horizontal)
	{
		cssProp.width = width;
		cssProp.left = left;
	}

	//check the current position
//	if (positionType == 'static')
//	{
//		$self.parent().css("position","relative");
//	}
	
	//aplying the css
	$self.css(cssProp);
  });

};

Array.prototype.contains = function(obj)
{
  var i = this.length;
  while (i--)
  {
    if (this[i] == obj)
    {
      return true;
    }
  }
  
  return false;
}

String.prototype.startsWith = function(value, ignoreCase)
{
  if (ignoreCase)
  {
    return (value.toLowerCase() == this.substring(0, value.length).toLowerCase());
  }
  else
  {
    return (value == this.substring(0, value.length));
  }
} 
  
String.prototype.endsWith = function(value, ignoreCase)
{
  if (ignoreCase)
  {
    return (value.toLowerCase() == this.substring(this.length - value.length).toLowerCase());
  }
  else
  {
    return (value == this.substring(this.length - value.length));
  }
} 

String.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/g,"");
}

String.prototype.ltrim = function()
{
	return this.replace(/^\s+/,"");
}

String.prototype.rtrim = function()
{
	return this.replace(/\s+$/,"");
}

function isNumeric(value)
{
	if (value * 1 == NaN)
		return false;

	return true; 
}

var popupId = "";

//loading popup with jQuery magic
function loadPopup(popupElementId, backgroundElementId)
{
  //loads popup only if it is disabled
  if (popupId == "")
  {
    var POPUP_HEIGHT_BUFFER = 100;
	var POPUP_WIDTH_BUFFER = 100;
	var POPUP_MIN_HEIGHT = 100;
	var POPUP_MIN_WIDTH = 100;
	
	var background = null;
    if (backgroundElementId)
      background = $("#" + backgroundElementId);
    else
      background = $("#backgroundPopup");
    
    background.css("opacity", "0.7");

    var divPopup = $("#" + popupElementId);
    var divTitle = divPopup.find(".dvTitle");

    divPopup.css("top", $(window).height() + 100);

    background.fadeIn("slow");
    
    divPopup.fadeIn("slow", function()
    {
        var divBody = divPopup.find(".dvBody");

//    	alert("divBody.width = " + divBody.width());
    	
    	if (divPopup.width() > (divBody.width() + 20))
    	{
    		divPopup.width((divBody.width() + 20));
    	}
    	
        var windowHeight = $(window).height();
        var height = divPopup.height();
        
        if ((height + POPUP_HEIGHT_BUFFER) > windowHeight)
        {
        	height = windowHeight - POPUP_HEIGHT_BUFFER;
        	var contentHeightDiff = divPopup.height() - divBody.height();
        	if (contentHeightDiff > 0)
        		height -= contentHeightDiff;
        	
        	if (height < POPUP_MIN_HEIGHT)
        		height = POPUP_MIN_HEIGHT;
        	
        	divBody.height(height);
        }

        // adjust the width for the vertical scrollbar
        if (divBody.attr("scrollHeight") > divBody.height())
        {
        	var width = divPopup.width();
        	width += 16;
        	divPopup.width(width);
        }

//        if (divBody.attr("scrollWidth") > divBody.width())
//        {
//        	alert('1 width = ' + divBody.width() + "\nscrollWidth = " + divBody.attr("scrollWidth"));
//        	var width = divBody.attr("scrollWidth") + 20;
//        	divPopup.width(width);
//        }

        var windowWidth = $(window).width();
        var width = divPopup.width();

//    	alert('width + buffer = ' + (width + POPUP_WIDTH_BUFFER));

//    	alert("divBody.width = " + divBody.width());

        
        if ((width + POPUP_WIDTH_BUFFER) > windowWidth)
        {
            width = windowWidth - POPUP_WIDTH_BUFFER;

//        	alert('windowWidth = ' + windowWidth);

            if (width < POPUP_MIN_WIDTH)
            	width = POPUP_MIN_WIDTH;

            divPopup.width(width);
        }

        $("#" + popupElementId).center();
    });
    
    popupId = popupElementId;
  }
}

//disabling popup with jQuery
function disablePopup()
{
  //disables popup only if it is enabled
	
  if (popupId != "")
  {
    $("#backgroundPopup").fadeOut("slow");
    $("#" + popupId).fadeOut("slow");
    popupId = "";
  }
}

function updateMenu(pageId)
{
  if (pageId == "")
	  return;
  
  var pageIds = new Array("aboutUs", "createPlan", "home", "howTo", "myPlan", "why", "zipSavings", "zipEd", "zipSource");
  
  if (pageIds.contains(pageId))
  {
	  $("." + pageId).toggleClass(pageId+"Selected");
  }
  else
  {
	  alert("Invalid pageId:  " + pageId + "\n\nPlease use one of the following:\n\n   " + pageIds.toString());
  }
}

function updateAdminMenu(pageId)
{
  if (pageId == "")
	  return;
	  
  var pageIds = new Array("cacheManager", "createPartner", "createPartnerContent", "createZtoGUser",
		  "createZtoGContent", "findPartner", "findUsers", "findContent" );
	  
  if (pageIds.contains(pageId))
  {
	  $("#" + pageId + " a").toggleClass("active");
  }
  else
  {
	  alert("Invalid pageId:  " + pageId + "\n\nPlease use one of the following:\n\n   " + pageIds.toString());
  }
}

function deleteImage(imageType)
{
  $("#" + imageType + "Remove").attr("value", "true");
  $("#" + imageType).hide();
}

/*
 * Home Page Tab Rotation
 */
function TabData(tabBackgroundImageName, tabButtonImageName, tabButtonUrl, tabButtonTop, tabButtonLeft, tabButtonHeight, tabButtonWidth)
{
  var imagePath = CONTEXT_PATH + "/resources/images/";
  this.tabBackgroundImage = loadImage(imagePath + tabBackgroundImageName);
  
  if (tabButtonImageName)
    this.tabButtonImage = loadImage(imagePath + tabButtonImageName);
  this.tabButtonUrl = tabButtonUrl;
  this.tabButtonTop = tabButtonTop;
  this.tabButtonLeft = tabButtonLeft;
  this.tabButtonHeight = tabButtonHeight;
  this.tabButtonWidth = tabButtonWidth;
}

function TabRotation(tabDataItems)
{
  this.tabId = 0;
  this.tabDataItems = tabDataItems;
  
  this.element = document.getElementById("tabContent");
  //this.delay = delay;
  this.timer = null;
  
  var instance = this;
  
  instance.initialize();
  instance.rotate();
}

TabRotation.prototype.initialize=function()
{
  var instance = this;
  
  $(instance.element).mouseleave(function()
  {
    instance.tabMouseOut();
  });
}

TabRotation.prototype.rotate=function()
{
  var instance = this;
  
  instance.updateTab(instance.tabId);
  
  instance.tabId = ((instance.tabId + 1) % instance.tabDataItems.length);

  //instance.timer = setTimeout(function(){instance.rotate()}, instance.delay);
}

TabRotation.prototype.updateTab=function(tabId)
{
  var instance = this;

  var tabData = instance.tabDataItems[tabId];
	  
  updateBgImage(instance.element, tabData.tabBackgroundImage.src);
  
//  alert("tabData.tabBgImage = " + tabData.tabBgImage.src);
//  instance.element.style.backgroundImage = tabData.tabBgImage;

  var dvButton = $(instance.element).find(".tabButton");

  dvButton.hide();

  dvButton.each(function()
  {
	removeBgImage(this);
  });

  dvButton.unbind('mouseenter').unbind('mouseleave');
  
  if (tabData.tabButtonImage)
  {
    dvButton.hover(
      function ()
      {
        updateBgImage(this, tabData.tabButtonImage.src);
      }, 
      function ()
      {
        removeBgImage(this);
      }
    );
  }
	  
  dvButton.click(function()
  {
	window.location = tabData.tabButtonUrl;
  });
	  
  dvButton.css("top", tabData.tabButtonTop);
  dvButton.css("left", tabData.tabButtonLeft);
  dvButton.css("height", tabData.tabButtonHeight);
  dvButton.css("width", tabData.tabButtonWidth);

  dvButton.show();
}

TabRotation.prototype.tabMouseOver=function(tabId)
{
  var instance = this;

  //if (instance.timer)
  //{
    //clearTimeout(instance.timer);
    //instance.timer = null;
  //}

  instance.tabId = ((tabId + 1) % instance.tabDataItems.length);
	
  instance.updateTab(tabId);
}

TabRotation.prototype.tabMouseOut=function()
{
  var instance = this;
  
//  if (!instance.timer)
  //  instance.timer = setTimeout(function(){instance.rotate()}, instance.delay);
}

function updateBgImage(element, imagePath)
{
  var newImage = "url(" + imagePath + ")";
  element.style.backgroundImage = newImage;
  element.style.backgroundRepeat = "no-repeat";
}

function removeBgImage(element)
{
  element.style.backgroundImage = "none";
}

function loadImage(imagePath)
{
  var img = new Image();
  img.src = imagePath;
  
  return img;
}

//displayTagPageChange
//provides ability for the user to enter page number to change changes
function displayTagPageChange(requestUri, displayTagPageParam, pageField, event, maxPage)
{
  var characterCode;

  if(event.which) //if which property of event object is supported (NN4)
  { 
    characterCode = event.which;
  }
  else
  {
    characterCode = event.keyCode; //character code is contained in IE's keyCode property
  }

  if (characterCode == 13) //if generated character code is equal to ascii 13 (if enter key)
  {
    var value = pageField.value;
    if (value < 1)
      value = 1;
    else if (value > maxPage)
      value = maxPage;
    
    var pattern = displayTagPageParam + '=[0-9]+'
    
    var re = new RegExp(pattern);
    
    requestUri = requestUri.replace(re, '');
    
    var url = requestUri + "&" + displayTagPageParam + "=" + value;

    window.location = url;
  
    return false;
  }
  else if (characterCode < 48 || characterCode > 57) // only numbers are allowed
  {
    return false;
  }
  else
  {
    return true 
  }
}

function adjustHeight(leftDiv, rightDiv)
{
  var leftDivHeight = $("#" + leftDiv).height();
  var rightDivHeight = $("#" + rightDiv).height();

  var height = (leftDivHeight > rightDivHeight) ? leftDivHeight : rightDivHeight;
  
  $("#" + leftDiv).height(height);
  $("#" + rightDiv).height(height);
}

