/** 
 **  Copyright (c) 2005 Snapvine, LLC. All rights reserved.
 **
 ** THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Snapvine, LLC
 **    The copyright notice above does not evidence any
 **    actual or intended publication of such source code.
 **/


/** Utility methods for IE/moz compat
 **/

function ui_setVisible(id, show)
{
  elem = id ? document.getElementById(id) : null;
  if (elem)
    elem.style.display = show ? "" : "none";
}

function ui_getWindowWidth()
{
	if (window.innerWidth) // NS/Firefox
		return window.innerWidth;
	else if (document.all) // IE
		return document.body.clientWidth;
}

function ui_getWindowHeight()
{
	if (window.innerHeight) // NS/Firefox
		return window.innerHeight;
	else if (document.all) // IE
		return document.body.clientHeight;
}

function ui_getPageScrollX() {
  if( typeof( window.pageYOffset ) == 'number' )
  {
      //Netscape compliant
      scrOfX = window.pageXOffset;
  }
  else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) )
  {
      //DOM compliant
      return document.body.scrollLeft;
  }
  else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) )
  {
      //IE6 standards compliant mode
      return document.documentElement.scrollLeft;
  }
  return 0;
}

function ui_getPageScrollY() {
  if( typeof( window.pageYOffset ) == 'number' )
  {
    //Netscape compliant
    return window.pageYOffset;
  }
  else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) )
  {
    //DOM compliant
    return document.body.scrollTop;
  }
  else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) )
  {
    //IE6 standards compliant mode
    return document.documentElement.scrollTop;
  }
  return 0;
}

function ui_setCursor(name)
{
	document.body.style.cursor = name;
	
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		links = document.getElementsByTagName('A');
		for (ii=0;ii<links.length;ii++){
			links[ii].save_cursor = links[ii].style.cursor;
			links[ii].style.cursor = name;
		}
	}else{
		document.body.setCapture();
	}
}

function ui_resetCursor()
{
	document.body.style.cursor = "default";
	
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		links = document.getElementsByTagName('A');
		for (ii=0;ii<links.length;ii++){
			links[ii].style.cursor = links[ii].save_cursor;
		}
	}else{
		document.body.releaseCapture();
	}
}

function ui_show(val)
{
	document.getElementById(val).style.display="inline";
}

function ui_hide(val)
{
	document.getElementById(val).style.display="none";
}

function ui_toggle(val)
{
	if (document.getElementById(val).style.display == "none"){
		ui_show(val);
	}else{
		ui_hide(val);
	}
}

function ui_enable(val)
{
	document.getElementById(val).disabled=false;
}

function ui_disable(val)
{
	document.getElementById(val).disabled=true;
}

function ui_limit_text(limitField, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		//limitCount.value = limitNum - limitField.value.length;
	}
}

function ui_get_child_node_by_id(node, id)
{
	child = node.firstChild;
	matches = new Array;
		
	while(child){
		if (child.id == id){
			matches.append(child);
		}
		child = child.nextSibling;
	}

	if (matches.size > 1){
		return matches;
	}else if (matches.size == 1){
		return matches[0];
	}else{
		return 0;
	}
}
	

function ui_make_visible(popup, x, y, w, h)
{
	x += ui_getPageScrollX();
	y += ui_getPageScrollY();

    w_w = ui_getPageScrollX() + ui_getWindowWidth();
    w_h = ui_getPageScrollY() + ui_getWindowHeight();
    
    if (x < 0){
        x = 0;
    }else if(x + w > w_w){
        x = w_w - w;
    }
    
    if (y < 0){
        y = 0;
    }else if(y + h > w_h){
        y = w_h - h;
    }

    popup.style.left = x + "px";
    popup.style.top = y + "px";
}

/**
 ** This method is used to apply the IE-only alpha transparency filter to .png images
 ** for IE5.5 and IE6 so that alpha-transparency .png images look like they should.
 **/
function ui_fix_alpha_transparency()
{
  if (!$.browser.msie || typeof document.body.style.maxHeight != 'undefined')
  {
    // If the user isn't running IE or their browser supports maxHeight (IE7+), then we can skip all this nonsense.
    // IE7 does actually support the filter, but why do the extra processing if we don't need to.
    return;
  }
  
  $('img.alpha_transparent').each(function()
  {
    var img_name = $.trim(this.src.toLowerCase());
    
    // The next five lines deal with those numeric strings at the end of Ruby-generated images.
    var q = img_name.indexOf('?');
    if (q == -1)
    {
      q = img_name.length;
    }
    
    if (img_name.substring((q - 4), q) != '.png')
    {
      // Not a PNG image, so we ll "continue"
      return true;
    }
    
    img_name = img_name.substring(0, q);
    
    var img_parent = this.parentNode;
    if (img_parent.tagName.toLowerCase() == 'a')
    {
      img_parent = img_parent.parentNode;
    }
    
    // Apply the IE-only filter to the parent <div>
    img_parent.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + img_name + "', sizingMethod='scale')";
    
    // Then hide the image
    this.style.display = 'none';
  }
  );
}

/** This class implements a simple popup dialog with drop shadow. To us it,
 ** derive a class from this one and implement the draw method. See the record
 ** popup for an example on how to use this little punk.
 **/
 
var SnapvinePopup = Class.create();
SnapvinePopup.prototype = {
	
  makeVisible: function(x, y)
  {
	  d_w = this.popup.clientWidth;
	  d_h = this.popup.clientHeight;
	  
	  w_w = ui_getWindowWidth() + ui_getPageScrollX();
	  w_h = ui_getWindowHeight() + ui_getPageScrollY();
	  
	  if (x < 0){
		  x = 0;
	  }else if(x + d_w > w_w){
		  x = w_w - d_w;
	  }

	  if (y < 0){
		  y = 0;
	  }else if(y + d_h > w_h){
		  y = w_h - d_h;
	  }

	  this.popup.style.left = x + "px";
	  this.popup.style.top = y + "px";
  },
  
  close: function(index)
  {
	  document.body.removeChild(this.popup);
    document.body.popups[index] = null;
    return false;
  },

  show: function(x, y)
  {
	  x += ui_getPageScrollX();
	  y += ui_getPageScrollY();
	  
    this.popup.style.width = (this.options.width ? this.options.width : "300")+"px"
    if (x < 10)
      x = 10
    else if (x+parseInt(this.popup.style.width) > ui_getWindowWidth()-10)
      x = ui_getWindowWidth()-parseInt(this.popup.style.width)-20
    
    if (y < 10)
      y = 10
    else if (y > ui_getWindowHeight())
      y = ui_getWindowHeight()-parseInt(this.popup.getHeight())-10
    
	  this.popup.style.left = x + "px";
	  this.popup.style.top = y + "px";
	  this.popup.style.zIndex = 1000;
	  this.popup.style.position = "absolute";
	  this.popup.style.visibility = "hidden";
	  this.popup.style.display = "inline";
	  
	  this.makeVisible(x,y);

	  this.popup.style.visibility = "visible";
  },

  create: function()
  {
	  this.popup = document.createElement("div");
    
    if (!document.body.popups) document.body.popups = new Array();
    if (!this.options.title_color) this.options.title_color="#EEEEEE";

	  this.popup.setAttribute("class", "popup_container");
	  html = "<div class='pop_window' style='"+this.options.title_style+"'>";
    html += "<div class='pop_title'>";
    html += "<div class='pop_actions' style='width: 20px; float: right;'><a href='#' onclick='document.body.popups["+document.body.popups.length+"].close()'>X</a></div>";
    html += this.options.title+"</div>";
	  html += "<div class='pop_content'>"+this.draw()+"</div>";
	  html += "</div>";
	  this.popup.innerHTML = html;
	  this.popup.style.display = "none";
	  document.body.appendChild(this.popup);
    
    document.body.popups[document.body.popups.length]=this;
  }
};



/** CountDown class is a simple class that implements a count down timer.
 ** 
 ** Params:
 ** e_time - element that should be updated with the time remaining
 ** is_terminated - callback function to check if the count down should be terminated
 ** on_completed - callback function for when the count down is done
 **/

var CountDown = Class.create();
CountDown.prototype = {
	initialize: function(expiration_date,
						 e_time,
						 is_terminated,
						 on_complete)
	{
        this.terminate = false;

		this.expiration_date = expiration_date;
		this.e_time = e_time;
		this.is_terminated = is_terminated || Prototype.emptyFunction;
		this.on_complete = on_complete || Prototype.emptyFunction;
		
		this.update_expire();
	},
	
	stop: function()
	{
		this.terminate = true;
	},
	
	update_expire: function()
	{
        if (this.is_terminated() || this.terminate)
		{
            return;
		}
		
		var now = new Date();
		if (now > this.expiration_date)
		{
			this.on_complete();		  
		}else{
			var diff = new Date();
			diff.setTime(this.expiration_date.getTime() - now.getTime())
			seconds = (diff.getSeconds() >= 10 ? "" : "0") + diff.getSeconds();
			expire_string = diff.getMinutes() + ":" + seconds + " minutes";
			if (diff.getMinutes() < 1)
			{
				expire_string = seconds + " seconds";
			}
			
			$("#"+this.e_time).html(expire_string);
			
			setTimeout((function(){this.update_expire()}).bind(this), 1000);
		}
	}
};

var DotDotDot = Class.create();
DotDotDot.prototype = {
	initialize: function(e_dots)
	{
		this.terminate = false;
		this.dots = 0;
		this.e_dots = e_dots;
		
		this.dot_dot_dot();
	},
	
	stop: function()
	{
		this.terminate = true;
	},
	
	dot_dot_dot: function()
	{
		if (this.terminate)
		{
			return;
		}
		
		this.dots++;
		var str = "";
		if (this.dots > 4) this.dots = 0;
		for ( i = 0; i < this.dots; ++i)
		{
			str = str + ".";
		}

		$('#'+this.e_dots).html(str);  

		setTimeout((function(){this.dot_dot_dot()}).bind(this), 550);
	}
};

// Use this method to get parameters from the current url
function get_param(name) {
  var qs = window.location.search.substring(1);
  var name = name + "=";
  if (qs.length > 0) {
    s = qs.indexOf(name);
    if (s != -1) {
      s += name.length;
      e = qs.indexOf("&",s);
      if (e == -1) {
        e = qs.length
      }
      return unescape(qs.substring(s, e));
    }
    return null;
  }
}

// Use this to set state of a status div (todo: make this an object)
function status_set_state(name, state) {
  var status_elt = document.getElementById("stat_" + name);
  var cur_status = "stat_" + name + "_" + state;
  var a = status_elt.childNodes;
  for (i=0;i<a.length;i++) {
    if (a[i].nodeType == 1) {
      if (a[i].id == cur_status) {
        a[i].style.display = "block";
      } else {
        a[i].style.display = "none";
      }
    }
  }
}

function status_set_info(name, data) {
  var status_elt = document.getElementById("stat_" + name + "_info");
  status_elt.value = data;
}

function status_get_info(name, data) {
  var status_elt = document.getElementById("stat_" + name + "_info");
  return status_elt.value;
}


function ui_findPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent)
	{
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent)
		{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft,curtop];
}

function ui_modal_on(zIndex)
{
  document.getElementById("overlay").style.display='block';
  if (zIndex) document.getElementById("overlay").style.zIndex=zIndex;
}

function ui_modal_off()
{
  document.getElementById("overlay").style.display='none';
}

function ui_enforce_height_and_width(img, max_height, max_width)
{
  original_width = img.width;
  aspect_ratio = img.height/img.width;
  
  if (aspect_ratio == 1)
    img.width = img.height = (max_height > max_width) ? max_width : max_height;
  else
  {
    if (img.width > max_width)
    {
      img.width = max_width;
      img.height = max_width*aspect_ratio;
    }
    if (img.height > max_height)
    {
      img.width = max_height/aspect_ratio;
      img.height = img.width*aspect_ratio;
    }
  }
  return original_width;
}

/*
 * Function modified from:
 * http://www.faqts.com/knowledge_base/view.phtml/aid/13562/fid/130
 */
function ui_replace_selection (input, replaceString)
{
  if (input.setSelectionRange)
  {
    var selectionStart = input.selectionStart;
    var selectionEnd = input.selectionEnd;
    input.value = input.value.substring(0, selectionStart)
                  + replaceString
                  + input.value.substring(selectionEnd);
    input.focus();
    if (selectionStart != selectionEnd) // has there been a selection
      input.setSelectionRange(selectionStart, selectionStart + replaceString.length);
    else // set caret
    {
      pos = selectionStart + replaceString.length;
      input.setSelectionRange(pos, pos);
    }
  }
  else if (document.selection)
  {
    var range = document.selection.createRange();
    if (range.parentElement() == input) {
      var isCollapsed = range.text == '';
      range.text = replaceString;
      if (!isCollapsed)  { // there has been a selection
        //it appears range.select() should select the newly 
        //inserted text but that fails with IE
        range.moveStart('character', -replaceString.length);
        range.select();
      }
    }
  }
}