var g_request = null;
var g_current_page = "index";

// key: anchor tag / descriptive name for page. This is a global since it's dynamic; wordpress
// pages can be added to this object and 
// value: array [0]: tab number, 
//              [1]: whether the page should be cached (i.e. contains static content)
//              [2]: web page URL
//              [3]: custom response handler after loading page
var g_pages = {
  "index":           [1, false,  "/pages/page_index.php"],
  "news":            [2, false,  "/pages/page_news.php"],
  "software":        [3, false,  "/pages/page_software.php"],
  "about":           [4, false,  "/pages/page_about.php"],
  "contact":         [5, false,  "/pages/page_contact.php", loadContactUsPageResponse],
  "contact_thanks":  [5, false,  "/pages/page_contact_thanks.php"]
}


// main Ajax server request function
function httpRequest(reqType, url, asynch, responseHandle)
{
  // Mozilla-based browsers
  if (window.XMLHttpRequest)
    g_request = new XMLHttpRequest();
  else if (window.ActiveXObject)
  {
    g_request =  new ActiveXObject("Msxml2.XMLHTTP");
    if (!g_request)
      g_request =  new ActiveXObject("Microsoft.XMLHTTP");
  }

  // unlikely, but we test for a null request if neither ActiveXObject was initialized
  if (g_request)
  {
    // if the reqType parameter is POST, then the 5th argument to the function is the POSTed data
    if (reqType.toLowerCase() != "post")
      initReq(reqType, url, asynch, responseHandle)
    else
    {
      var args = arguments[4];
      if (args != null && args.length > 0)
        initReq(reqType, url, asynch, responseHandle, args);
    }
  }
  else
  {
    alert("Sorry, your browser looks pretty old, so this site won't function "
		    + "properly for you. Time to upgrade... - or send us a nasty note "
				+ "telling us there's a bug with the site.");
  }
}


function initReq(reqType, url, bool, responseHandle)
{
  try
  {
    // specify the function that will handle the HTTP response
    g_request.onreadystatechange = responseHandle;
    g_request.open(reqType, url, bool);

    if (reqType.toLowerCase() == "post")
    {
      g_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset:UTF-8");
      g_request.send(arguments[4]);
    }
    else
    {
      g_request.send(null);
    }
  }
  catch (errv)
  {
	  // need to update
    alert("The application cannot contact the server at this moment. Please wait and try again.");
  }
}


// onload handler for main page. Inits the RSH history object and loads the appropriate page (from
// query string)
function onPageLoad()
{
  dhtmlHistory.initialize();
  dhtmlHistory.addListener(handleHistoryChange);

	var initialLocation = dhtmlHistory.getCurrentLocation();
  updateUI(initialLocation, null);
}


function selectPage(page)
{
  // request type (POST/GET)default page and Ajax response handler 
  var requestType = "post";
  var default_page = "pages/page_index.php";
  responseFunction = loadPageResponse;

	// find out which URL we're going to load 
	var url = (g_pages[page]) ? g_pages[page][2] : default_page;

	// set the response handler for cached/static pages
	if (g_pages[page][1])
	  responseFunction = loadCachePageResponse;

	// if a specific response handler is mentioned, use that instead.
	if (g_pages[page][3])
	  responseFunction = g_pages[page][3];

  // store the page for google tracking
//  urchinTracker(page);
	pageTracker._trackPageview(page);

  // keep track of this page in memory for the browser's BACK button
  dhtmlHistory.add(page, page);

  // update the current page and keep track of the last one
  var old_page = g_current_page;
  g_current_page = page;


	// update the selected tab
  $("tab" + g_pages[old_page][0]).src = "/images/tab" + g_pages[old_page][0] + "_unselected.jpg";
  $("tab" + g_pages[g_current_page][0]).src = "/images/tab" + g_pages[g_current_page][0] + "_selected.jpg";

  if (g_current_page != "news")
    $("tab2").src = "/images/tab2_unselected.jpg";  

  // if this is a static page and already stored in cache, load it from there instead of the server 
  if (g_pages[g_current_page][1] && historyStorage.hasKey(g_current_page + "_HTML"))
  {
	  $("content").innerHTML = historyStorage.get(g_current_page + "_HTML");

  	if (g_current_page == "index")
    {
      $("product_1").style.display = "block";
      $("product_2").style.display = "block";
      $("product_3").style.display = "block";
    }    
  }
	else
	{
	  // show the "loading" animated gif
    start_processing();

    // get the page
		var data = "a=1"; // for IE
    httpRequest("post", url, true, responseFunction, data);
  }

  return false;
}


function loadPageResponse()
{  
  if (g_request.readyState == 4)
  {
    if (g_request.status == 200)
    {
      var rawResponse  = g_request.responseText;
      $("content").innerHTML = rawResponse;

			if (g_current_page == "index")
      {
        new Effect.Appear('product_1', { delay: 0, duration: 0.8 });
        new Effect.Appear('product_2', { delay: 0.5, duration: 0.8 });
        new Effect.Appear('product_3', { delay: 1, duration: 0.8 });
      }

      end_processing();
    }
    else
      alert(g_request.status);
  }
}


function loadCachePageResponse()
{  
  if (g_request.readyState == 4)
  {
    if (g_request.status == 200)
    {
      var rawResponse  = g_request.responseText;
      $("content").innerHTML = rawResponse;
			historyStorage.put(g_current_page + "_HTML", rawResponse);

			if (g_current_page == "index")
      {
        new Effect.Appear('product_1', { delay: 0, duration: 0.8 });
        new Effect.Appear('product_2', { delay: 0.5, duration: 0.8 });
        new Effect.Appear('product_3', { delay: 1, duration: 0.8 });
      }

      end_processing();
    }
    else
      alert(g_request.status);
  }
}


function loadContactUsPageResponse()
{
  if (g_request.readyState == 4)
  {
    if (g_request.status == 200)
    {
      var rawResponse  = g_request.responseText;
      $("content").innerHTML = rawResponse;
			historyStorage.put("contact_us_HTML", rawResponse);
      document.contact_form.company.focus();

      end_processing();
    }
  }
}


/** This function is called whenever the user presses the back or forward buttons. This
    function will be passed the newLocation, as well as any history data we associated with 
	the location. */
function handleHistoryChange(newLocation, historyData)
{
  updateUI(newLocation, historyData);                       
}


// A simple RSH method that updates our user interface using the new location.
// ** newLocation is any anchor tag, denoting a specific page.
function updateUI(newLocation, historyData)
{
  if (!newLocation) 
    newLocation = "index";

  selectPage(newLocation);
}


function start_processing()
{
  $("page_loading_icon").style.display = "block";
	
	// for IE...
	setTimeout('$("page_loading_icon").src="/images/loading.gif"', 200);
}

function end_processing()
{
  $("page_loading_icon").style.display = "none";
}

// ------------------------------------------------------------------------------------------------

function submitContactUs(f)
{
  var url = "http://www.blacksheepsoft.com/admin/process.php";

  var name = f.name.value;
  var email = f.email.value;
  var subject = f.subject.value;
  var comments = f.comments.value;
  var data = "name=" + name + "&email=" + email + "&subject=" + subject + "&comments=" + comments + "&form_tools_form_id=1";

  if (!name)
  {
    alert("Please enter your name.");
    f.name.focus();
    return false;
  }
  else if (!email)
  {
    alert("Please enter your email address.");
    f.email.focus();
    return false;
  }
  else if (!subject)
  {
    alert("Please enter the email subject.");
    f.email.focus();
    return false;
  }
  else if (!comments)
  {
    alert("Please enter your comments.");
    f.comments.focus();
    return false;
  }

  start_processing();
  httpRequest("post", url, true, handleSubmitContactUsResponse, data);

  return false;
}


function handleSubmitContactUsResponse()
{
  if (g_request.readyState == 4)
  {
    if (g_request.status == 200)
    {
      end_processing();
      selectPage("contact_thanks");
    }
    else
      alert(g_request.status);
  }
}

// -----------------------------------------------------------------------------------------------


Array.prototype.contains = function(value)
{
  var found = false;

  for (j=0; j<this.length; j++)
  {
    if (this[j] == value)
      found = true;
  }
  return found;
}


// --------------------------------------------------------------------------
// postit.js v1.0
// written by: Benjamin Keen, August 2003
// --------------------------------------------------------------------------
// For an explanation of the script, see attached example.html, or visit 
// benjaminkeen.org


/* ------------------------------------------------------------------------*/
// CONFIGURATION SETTINGS

// Default styles
var postitStyles = new Object();

postitStyles = {
  'width':                  '200',
  'height':                 'auto',   
  'backgroundColor':        '#FFFFCC',
  'fontFamily':             'verdana', 
  'fontSize':               '8pt', 
	
  'padding':                '8px',
  'border':                 '1px solid #999999',
  'position':               'absolute',
  'z-index':                '100'
}

var _x_offset = 10;      // # of pixels x is offset from location of mouse click   
var _y_offset = 10;      // # of pixels y is offset from location of mouse click

/* ------------------------------------------------------------------------*/



// --------------------------------------------------------------------------
// function:    initializePostits() 
// description: called by body onload handler. This automatically hides all 
//              post-its on the page. Post-its are identified by having an 
//              id with this format: id="postitX" - where X is any integer. 
// --------------------------------------------------------------------------
function initializePostits() {

  // find all post-its 
	var postits = document.getElementsByTagName('div');
	var postitElementsArray = new Array();         // stores id's of all post-its

	for (i=0; i<postits.length; i++) {
    if (postits[i].id.match(/^postit/i)) { 
		  postitElementsArray.push(postits[i].id);
		}
	}
		
	// hide all post-its
  for (i=0; i<postitElementsArray.length; i++) {
	  $(postitElementsArray[i]).style.display = "none";
	}

	
	// set default post-it styles. Individual post-it styles may be overridden 
	// later by showPostit()
	for (styleName in postitStyles) {

		// set style for each unique postit
    for (i=0; i<postitElementsArray.length; i++) {
			$(postitElementsArray[i]).style[styleName] = postitStyles[styleName]; 
	  }
	}
}


// --------------------------------------------------------------------------
// function:    currentMousePosition()
// description: helper function to store location of mouse in global var
//              so we can access those values in Netscape 
// --------------------------------------------------------------------------
window.onmousemove = currentMousePosition;
var _x;       // global var to keep track of x mouse co-ordinate
var _y;       // global var to keep track of y mouse co-ordinate

function currentMousePosition(e) {  
  if (document.layers || $&&!document.all) { 
	  _x = e.pageX;
		_y = e.pageY;
  }
} 


// --------------------------------------------------------------------------
// function:    showPostit()
// parameters:  - postitId: the unique id of the post-it (required)
//              - quadrant: 1=top-left, 2=top-right, 3=bottom-left, 4=bottom-right
//                          if 'null' uses default (optional)
//              - w:        width of post-it. if 'null' uses default (optional)
//              - h:        height of post-it. if 'null' uses default (optional)
//              - bc:       background color. if 'null' uses default (optional)
// --------------------------------------------------------------------------
function showPostit(postitId, quadrant, w, h, bc) {

	// Find x & y mouse location to figure out where to display the post-it
  var isIE = document.all ? true : false;	
	var x_coord = isIE ? event.clientX + document.body.scrollLeft : _x;
	var y_coord = isIE ? event.clientY + document.body.scrollTop  : _y;

  y_coord -= findPosY($("content"));
  x_coord -= findPosX($("content"));

	var postitStyle = $(postitId).style;
	
  
	// custom post-it size
	if (w) { postitStyle.width = w;	}
	if (h) { postitStyle.height = h;	}
	
	
  // toggle post-it visibility 
  if (postitStyle.display && postitStyle.display != 'none') { 
	  postitStyle.display = 'none';	
	}
	else { postitStyle.display = 'block'; }


	// calculate location of post-it. We do this *after* making it visible, since 
	// we can't ascertain the height of an element with 'auto' size unless it is 
	// visible. 
	var new_x_coord = x_coord + _x_offset;
	var new_y_coord = y_coord + _y_offset;

	var psw = Number(postitStyle.width.replace(/\D/g, ""));
	var psh = Number(postitStyle.height.replace(/\D/g, ""));
	
  if (psh == 0) { psh = $(postitId).offsetHeight; }

  switch (quadrant) {
	  case 1:                            // top-left
		  new_x_coord = x_coord - (psw + _x_offset);
		  new_y_coord = y_coord - (psh + _y_offset);
		  break;
		case 2:                            // top-right
		  new_x_coord = x_coord + _x_offset;
		  new_y_coord = y_coord - (psh + _y_offset);
		  break;		
		case 3:                            // bottom-left
		  new_x_coord = x_coord - (psw + _x_offset);
		  new_y_coord = y_coord + _y_offset;
		  break;		
		case 4:                            // bottom-right
		  new_x_coord = x_coord + _x_offset;
		  new_y_coord = y_coord + _y_offset;		
		  break;
	} 
	
  postitStyle.top  = new_y_coord;
  postitStyle.left = new_x_coord;

	// set the color
	if (bc) { postitStyle.backgroundColor = bc; }
	
	return false;
}


function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (1) 
		{
			curleft += obj.offsetLeft;
			if (!obj.offsetParent)
				break;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
  var curtop = 0;
  if (obj.offsetParent)
  {
	  while (1)
    {
      curtop += obj.offsetTop;
      if (!obj.offsetParent)
        break;
      obj = obj.offsetParent;
    }
	}

  else if (obj.y)
    curtop += obj.y;

  return curtop;
}
  
function _over(product_id)
{
  $("product_" + product_id).style.backgroundColor = '#E1F2FC';
}

function _out(product_id)
{
  $("product_" + product_id).style.backgroundColor = '#ffffff';
}
