function forceInt(x, y)
{
	return isNaN(y = parseInt(x))? 0 : y;
}

function getDivW(el)
{
	return forceInt(
		el ? (el.offsetWidth || el.style.pixelWidth || el.style.width || 0)
		: 0
	);
}

function getDivH(el)
{
	return forceInt(
		el ? (el.offsetHeight || el.style.pixelHeight || el.style.height || 0)
		: 0
	);
}

function nodeValue(node) {
    return (node.firstChild == null) ? '' : node.firstChild.nodeValue
}

function getAbsolutePosition(el)
{
	_absX = 0;
	_absY = 0;
	
	while (el)
	{
		_absX += forceInt(el.offsetLeft);
		_absX -= forceInt(el.scrollLeft);

		_absY += forceInt(el.offsetTop);
		_absY -= forceInt(el.scrollTop);
		
		el = el.offsetParent || null;
	}
}

function getOffsetPosition(el)
{
	_absX = 0;
	_absY = 0;
	
	while (el)
	{
		_absX += forceInt(el.offsetLeft);
		_absY += forceInt(el.offsetTop);
		
		el = el.offsetParent || null;
	}
}

// CALENDAR
//

function calendarFocus(divID)
{
    // Mark as focused
    eval('window.focus_' + divID + ' = true;');

    // Show popup
    showDiv(divID);
}

function calendarBlur(divID)
{
    // Mark as blurred
    eval('window.focus_' + divID + ' = false;');

    // If not moused over, hide popup
    eval('var over = window.over_' + divID + ';');
    if (!over)
        hideDiv(divID);
}

function calendarOver(divID)
{
    // Mark as moused over
    eval('window.over_' + divID + ' = true;');
}

function calendarOut(divID, e)
{
    if (window.event)
        e = window.event;
        
    var div = document.getElementById(divID);
    if (!div)
        return;

    var eventX = e.clientX + document.body.scrollLeft;
    var eventY = e.clientY + document.body.scrollTop;
    getAbsolutePosition(div);
    var divW = getDivW(div);
    var divH = getDivH(div);

    // Ignore this event if the cursor is inside the div
    if (eventX > _absX && eventX < _absX + divW && eventY > _absY && eventY < _absY + divH)
        return;
    
    // Mark as moused out
    eval('window.over_' + divID + ' = false;');

    // If not focused, hide popup
    eval('var focus = window.focus_' + divID + ';');
    if (!focus)
        hideDiv(divID);
}

// HOVER
//

function hoverOver(o)
{
    _hoverColor = o.style.backgroundColor;
    o.style.backgroundColor = '#CCCCCC';
}

function hoverOut(o)
{
    o.style.backgroundColor = _hoverColor;
}

function hoverClick(o)
{
    _hoverColor = '#EEEEEE';
}

// SHOW/HIDE

function showDiv(divID)
{
    var div = document.getElementById(divID);
    if (!div)
        return;

    div.style.visibility = 'visible';
}

function hideDiv(divID)
{
    var div = document.getElementById(divID);
    if (!div)
        return;

    div.style.visibility = 'hidden';
}

function hideDivTimeout(divID, time)
{
    setTimeout("hideDiv('" + divID + "')", time);
}

// UPLOAD
//

function preUpload(id) {
    var form = document.forms['aspnetForm'];
    var action = form.elements[id + '_Action'];
    var target = form.target;
    // Set values
    action.value = 'upload';    
    form.target = id + '_Target';
    
    // Submit form
    form.submit();

    // Restore values
    action.value = '';
    form.target = target;
}

function postUpload(id, filename)
{
    var hidden = document.getElementById(id + '_SlickBack');
    var slickback = hidden.value.replace("__FILE__", filename);

    eval(slickback);
}

function resizeIframe()
{
  var flyoutCart = document.getElementById('flyoutCart');
  var iFrame = document.getElementById('iFrame');
  alert(flyoutCart);
  alert(iFrame);
  
  var height = getDivH(flyoutCart);
  
  iFrame.style.height = height;
}

function goToLink(pSelect)
{
  if(pSelect[pSelect.selectedIndex].value.length == 0)
  {
    return;
  }
  else if (pSelect[pSelect.selectedIndex].value.substring(0, 4) == "http")
  {
    window.open(pSelect[pSelect.selectedIndex].value,'_blank');
  }
  else if (pSelect[pSelect.selectedIndex].value.substring(0, 3) == "www")
  {
    window.open("http://" + pSelect[pSelect.selectedIndex].value, '_blank');
  }
  else
  {
    window.open(pSelect[pSelect.selectedIndex].value, '_blank');
  }
}

// POPUPS
//

function popup(url, width, height, winId, scroll) {
  if (winId == null) {
  	time = new Date();
    winId = time.getTime().toString();
  }
  if (!winId.substr(0, 3) == 'rn_')
    winId = 'rn_' + winId;
	var wtop = (screen.height - height) / 2 - 30;
	var wleft = (screen.width - width) / 2;
	var ref = window.open(url,winId,'width='+width+',height='+height+',top='+wtop+',left='+wleft+
              ',resizable=yes,scrollbars=' + (scroll ? 'yes' : 'no') + ',toolbar=no,location=no,directories=no,status=yes,menubar=no,copyhistory=no');
  ref.focus();
  
  return ref;
}

function returnFromPopup()
{
    window.opener.refreshPage();
    window.close();
}

function returnFromProductPicker(editorID, productID, productName)
{
    var editor = window.opener.document.getElementById(editorID);
    editor.PasteHTML("<table id=\"PRODUCT:" + productID + "\"><tr><td class=\"cute_cart_box\">" + productName + " (ID=" + productID + ")</td></tr><tr><td class=\"cute_cart_description\">Insert description here</td></tr></table>");

    setTimeout('window.close();', 1);
}

function pageScroll() {
    	window.scrollBy(0,-50); 
    	if(document.body.scrollTop > 0)
    	  setTimeout('pageScroll()',5); 
}

function rotateImage()
{
  var timeoutID = document.getElementById('timeoutID');
  timeoutID.value = setTimeout('fire()', 10000);
}

function fire()
{
  SlickBack.fire('__PAGE', 'NEXT');
  rotateImage();
}

function DisableControl(controlId)
{
  var el = document.getElementById(controlId);
  el.style.visibility = 'hidden';
}

function EnableControl(controlId)
{
  var el = document.getElementById(controlId);
  el.style.visibility = 'visible';
}

function doBeforePaste(control)
{
   maxLength = control.attributes["maxLength"].value;
   if(maxLength)
   {
       event.returnValue = false;
   }
}

function doPaste(control)
{
   maxLength = control.attributes["maxLength"].value;
   value = control.value;
   if(maxLength){
        event.returnValue = false;
        maxLength = parseInt(maxLength);
        var o = control.document.selection.createRange();
        var iInsertLength = maxLength - value.length + o.text.length;
        var sData = window.clipboardData.getData("Text").substr(0,iInsertLength);
        o.text = sData;
    }
}

function LimitInput(control)
{
    if(control.value.length > control.attributes["maxLength"].value)
    {
        control.value = control.value.substring(0,control.attributes["maxLength"].value);
    }
}

var _embroideryWindow = null;
var webRoot = 'http://www.sleepyheads.com/';

function openEmbroideryWindow(_checkBox)
{
  var checkBox = document.getElementById(_checkBox);
  var checked = checkBox.checked;
  if(!checked)
    return;
    
  _embroideryWindow = popup(webRoot + 'Embroidery.aspx', 380, 600, 'emb', true);
}

function viewEmbroideryWindow(id)
{
  if (!_embroideryWindow)
      return;
      
  _embroideryWindow.location = webRoot + 'Embroidery.aspx?ID=' + id;
  _embroideryWindow = null;
}

var _quantityWindow = null;
function openQuantityWindow()
{
  var hasQuantity = false;
  /*check quantity from hidden inputs*/
  
  if(hasQuantity)
    return;
    
  _quantityWindow = popup(webRoot + 'Quantity.aspx', 380, 600, 'quantity', true);
}

function viewQuantityWindow(orderLineID, availableQOH, requestedQOH)
{  
  if(!_quantityWindow)
    return;
    
  var path = webRoot + 'Quantity.aspx?ID=' + orderLineID + '&availableQOH=' + availableQOH+ '&requestedQOH=' + requestedQOH + '&Embroidery=' + (_embroideryWindow != null);
  _quantityWindow.location = path;
  _quantityWindow = null;
}

function closeQuantityWindow()
{
  if(_quantityWindow)
    _quantityWindow.close();
}

function SwitchToEmbroidery(orderLineID)
{
  window.location = webRoot + 'Embroidery.aspx?ID=' + orderLineID;
}

function disableButton(btn_ID)
{
  var btn;
  if( document.getElementById )
      btn = document.getElementById(btn_ID);
  else if( document.all )
      btn = document.all[btn_ID];
  else if( document.layers )
      btn = document.layers[btn_ID];    
  if (!btn)
      return false;

  if(btn.disabled == true)
  {
    return false;
  }
  else
  {
    //btn.value = 'Processing';
    setTimeout("DelayedDisableControl('" + btn_ID + "')",5);
    return true;
  }
}

function DelayedDisableControl(btn_ID)
{
  var btn;
  if( document.getElementById )
      btn = document.getElementById(btn_ID);
  else if( document.all )
      btn = document.all[btn_ID];
  else if( document.layers )
      btn = document.layers[btn_ID];    
  if (!btn)
      return false;
      
  btn.disabled = true;
}

function CheckPromoCode(textBoxID)
{
  var textBox = document.getElementById(textBoxID);
  if(textBox.value.length == 0)
  {
    return confirm('You do not have a \'promo code\' entered for this discount. \nLeaving this blank will create a site wide discount that will be applied to all orders. \n\nAre you sure you wish to continue?');
  }
  else
  {
    return true;
  }
}

// TREE VIEW
//

function copyAttributes(source, target) {
    var i;
    var attrs = source.attributes;
    for (i = 0; i < attrs.length; i++) {
        var attr = attrs.item(i);

        if (attr.name == 'style')
            target.style.cssText = attr.value;
        else
            target.setAttribute(attr.name, attr.value);
    }
}

function treeClick(img) {
    img.className = (img.className == 'treeOpen') ? 'treeClosed' : 'treeOpen';
}

function treeViewExpand(node) {
    var dataList = node.getElementsByTagName('data');
    if (dataList.length == 0)
        return;

    var data = dataList[0];
    var id = data.getAttribute('id');
    var parent = document.getElementById(id);
    if (!parent)
        return;

    var root = parent.parentNode;
    var target = parent.nextSibling;

    var i;
    for (i = 0; i < data.childNodes.length; i++) {
        var row = data.childNodes[i];
        if (row.nodeType != 1)
            continue;

        if (row.nodeName == 'div') {
            var div = document.createElement('div');
            copyAttributes(row, div);
            div.innerHTML = nodeValue(row);

            root.insertBefore(div, target);
        }
        else {
            var tr = document.createElement('tr');
            copyAttributes(row, tr);

            root.insertBefore(tr, target);

            var j;
            for (j = 0; j < row.childNodes.length; j++) {
                var cell = row.childNodes[j];

                var td = document.createElement('td');
                copyAttributes(cell, td);
                td.innerHTML = nodeValue(cell);

                tr.appendChild(td);
            }
        }
    }
}

function treeViewCollapse(node) {
    var dataList = node.getElementsByTagName('data');
    if (dataList.length == 0)
        return;

    var data = dataList[0];
    var id = data.getAttribute('id');
    var parent = document.getElementById(id);
    if (!parent)
        return;

    var root = parent.parentNode;

    var current;
    var next = parent.nextSibling;
    while (next) {
        current = next;
        next = current.nextSibling;

        if (current.nodeType != 1)
            continue;

        var childID = current.getAttribute('id');
        if (!childID)
            continue;

        if (childID.substring(0, id.length) != id)
            break;

        root.removeChild(current);
    }
  }

  function checkCode(codeID) {
    code = document.getElementById(codeID);
    if (code == null)
      return true;

    if (code.value.length == 0)
      return confirm('Are you sure you wish to create a site-wide discount?');
      
    return true;
  }