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 getAbsolutePosition(el)
{
  var x = 0;
  var y = 0;
          
  while (el)
  {
    x += forceInt(el.offsetLeft);
    x -= forceInt(el.scrollLeft);

    y += forceInt(el.offsetTop);
    y -= forceInt(el.scrollTop);
    
    el = el.offsetParent || null;
  }

  return {"x": x, "y": y};
}

function getOffsetPosition(el)
{
    var x = forceInt(el.offsetLeft);
    var y = forceInt(el.offsetTop);

    return {"x": x, "y": y};
}

function nodeValue(node)
{
    return (node.firstChild == null) ? '' : node.firstChild.nodeValue
}

function toggleDiv(id)
{
    var div = document.getElementById(id);
    if (!div)
        return;
        
    div.style.display = (div.style.display == 'none') ? '' : 'none';
}

function togglePop(id) 
{
    var root = document.getElementById('popRoot');
    if (!root)
        return false;

    var result = false;

    var divs = root.getElementsByTagName('div');
    var header;
    var i;
    for (i = 0; i < divs.length; i++) {
        var div = divs[i];
        switch (div.className) {
            case 'popOpen':
            case 'popClosed':
                header = div;
                break;

            case 'popFloat':
                if (div.id == id && div.style.visibility == 'hidden') {
                    header.className = 'popOpen';
                    div.style.visibility = '';

                    result = true;
                }
                else {
                    header.className = 'popClosed';
                    div.style.visibility = 'hidden';
                }
                break;
        }
    }

    return result;
}

function setChecked(id, value) 
{
    var div = document.getElementById(id);
    if (!div)
        return;

    var inputs = div.getElementsByTagName('input');
    var i;
    for (i = 0; i < inputs.length; i++) {
        if (inputs[i].type != 'checkbox')
            continue;

        inputs[i].checked = value;
    }
}

// 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;
    var abs = getAbsolutePosition(div);
    var divW = getDivW(div);
    var divH = getDivH(div);

    // Ignore this event if the cursor is inside the div
    if (eventX > abs.x && eventX < abs.x + divW && eventY > abs.y && eventY < abs.y + 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);
}

// POPUP
//

function popup(url, width, height, winId, scroll)
{
    if (winId == null) {
        time = new Date();
        winId = time.getTime().toString();
    }
    if (!winId.substr(0, 3) == 'tn_')
        winId = 'tn_' + winId;

    var wtop = (screen.height - height) / 2 - 75;
    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=no,menubar=no,copyhistory=no');
    ref.focus();

    return ref;
}

function popupImage(url, width, height)
{
    popup(url, width, height, 'img', true);
}

// 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);
}

// UPS ADDRESS VERIFICATION
//

var _avUPSWindow = null;

function openUPSAddressVerification()
{
    _avUPSWindow = popup('UPSAddressEmpty.aspx', 450, 350, 'av', true);
}

function viewUPSAddressVerification(address)
{
    if (!_avUPSWindow)
        return;

    _avUPSWindow.location = 'UPSAddressVerification.aspx?Address=' + address;
}

// USPS ADDRESS VERIFICATION
//

var _avUSPSWindow = null;

function openUSPSAddressVerification()
{
    _avUSPSWindow = popup('USPSAddressEmpty.aspx', 600, 350, 'av', true);
}

function viewUSPSAddressVerification(address)
{
    if (!_avUSPSWindow)
        return;

    _avUSPSWindow.location = 'USPSAddressVerification.aspx?Address=' + address;
}

// 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); 
    }
}

// SEARCH FIELDS
// 

function searchFocus(f, c)
{
    if (f.value == f.title)
    {
        f.value = '';
        f.className = (c || 'input');
    }
}

function searchBlur(f, c)
{
    if (f.value == '')
    {
        f.value = f.title;
        f.className = (c || 'input') + ' grey';
    }
}

// CONTINUE SHOPPING

function continueSave(url)
{
    window.name = 'cs:' + url;
}

function continueGo(fallback)
{
    if (window.name && window.name.substring(0,3) == 'cs:')
    {
        window.location = window.name.substring(3);
        return;
    }
    
    window.location = fallback;
}

// DISABLE BUTTON

function disableGet(id)
{
    var f = null;
    if (document.getElementById)
        f = document.getElementById(id);
    else if(document.all)
        f = document.all[id];
    else if(document.layers)
        f = document.layers[id];    

    return f;
}

function disableButton(id)
{
    var f = disableGet(id);
    if (!f)
        return false;

    if (f.disabled == true)
    {
        return false;
    }
    else
    {
        // f.value = 'Processing';
        setTimeout("disableTimeout('" + id + "')", 5);
        return true;
    }
}
 
function disableTimeout(id)
{
    var f = disableGet(id);
    if (!f)
        return;
     
    f.disabled = true;
}

// ENTER EVENT
//

function genericPress(e, f) {
    var key;
    if (window.event)
        key = e.keyCode;
    else
        key = e.which;
    
    if (key == 10 || key == 13) {
        f.form.submit();
        return false;
    }

    return true;
}

// RSS CLIENT
//

function getFeed(webroot, index)
{
    // Load feed
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = webroot + '/Gateway.aspx?F=' + index;
    head.appendChild(script);
}

function handleFeed(divid, content) 
{
    var div = document.getElementById(divid);
    if (div)
        div.innerHTML = content;
}

// IMAGE ZOOM
//

var _zoomWindow;
var _zoomWindowWidth;
var _zoomWindowHeight;
var _zoomX;
var _zoomY;
var _zoomZ;
var _zoomWMin;
var _zoomWMax;
var _zoomRatio;
var _zoomSmallerButton;
var _zoomLargerButton;
var _zoomTrack;
var _zoomTrackDrag;
var _zoomTrackDragX;
var _zoomThumb;
var _zoomThumbXMin;
var _zoomThumbXMax;
var _zoomTimer = null;
var _zoomImage;

function zoomSetup(fullWidth, fullHeight) 
{
    // Reset
    zoomButtonStop();
    zoomTrackStop();

    if (_zoomSmallerButton) {
        _zoomWindow.onmousemove = null;
    }

    if (_zoomSmallerButton) {
        _zoomSmallerButton.onmousedown = null;
        _zoomSmallerButton.onmouseup = null;
    }

    if (_zoomLargerButton) {
        _zoomLargerButton.onmousedown = null;
        _zoomLargerButton.onmouseup = null;
    }

    if (_zoomTrack) {
        _zoomTrack.onmousedown = null;
        _zoomTrack.onmousemove = null;
        _zoomTrack.onmouseup = null;
        _zoomTrack.onmouseout = null;
    }

    _zoomWindowWidth = null;
    _zoomWindowHeight = null;
    _zoomX = null;
    _zoomY = null;
    _zoomZ = null;
    _zoomWMin = null;
    _zoomWMax = null;
    _zoomSmallerButton = null;
    _zoomLargerButton = null;
    _zoomTrack = null;
    _zoomTrackDrag = null;
    _zoomTrackDragX = null;
    _zoomThumb = null;
    _zoomThumbXMin = null;
    _zoomThumbXMax = null;
    _zoomRatio = null;
    _zoomImage = null;

    // Setup
    if (fullWidth <= 0 || fullHeight <= 0)
        return;

    var zoom = document.getElementById('zoom');
    if (!zoom)
        return;

    var zoomS = document.getElementById('zoomS');
    if (!zoomS)
        return;

    var zoomL = document.getElementById('zoomL');
    if (!zoomL)
        return;

    var zoomT = document.getElementById('zoomT');
    if (!zoomT)
        return;

    var zoomI = document.getElementById('zoomI');
    if (!zoomI)
        return;

    var images = zoomI.getElementsByTagName('img');
    if (images.length == 0)
        return;

    var zoomW = getDivW(zoom);
    var zoomSW = getDivW(zoomS);
    var zoomLW = getDivW(zoomL);
    var zoomTW = getDivW(zoomT);
    var range = zoomW - zoomSW - zoomLW - zoomTW;
    if (range <= 0)
        return;

    var zoomIW = getDivW(zoomI);
    var zoomIH = getDivH(zoomI);
    var wMin = Math.min(fullWidth, zoomIW);
    var wMax = Math.max(fullWidth, wMin * 4);

    _zoomWindow = zoomI;
    _zoomWindowWidth = zoomIW;
    _zoomWindowHeight = zoomIH;
    _zoomX = 0.5;
    _zoomY = 0.5;
    _zoomZ = 0;
    _zoomWMin = wMin;
    _zoomWMax = wMax;
    _zoomSmallerButton = zoomS;
    _zoomLargerButton = zoomL;
    _zoomTrack = zoom;
    _zoomTrackDrag = false;
    _zoomTrackDragX = 0;
    _zoomThumb = zoomT;
    _zoomThumbXMin = zoomSW;
    _zoomThumbXMax = zoomSW + range;
    _zoomRatio = fullHeight / fullWidth;
    _zoomImage = images[0];

    _zoomImage.style.position = 'absolute';
    _zoomImage.style.left = '0px';
    _zoomImage.style.right = '0px';

    _zoomWindow.onmousemove = zoomWindowMove;

    _zoomSmallerButton.onmousedown = function () { zoomButtonStart(-1); }
    _zoomSmallerButton.onmouseup = zoomButtonStop;

    _zoomLargerButton.onmousedown = function () { zoomButtonStart(1); }
    _zoomLargerButton.onmouseup = zoomButtonStop;

//    _zoomThumb.onmouseout = function (e) {
//        if (window.event)
//            e = window.event;

//        e.cancelBubble = true;
//        if (e.stopPropagation) e.stopPropagation();
//            
//        return false; 
//    }

    _zoomTrack.onmousedown = zoomTrackStart;
    _zoomTrack.onmousemove = zoomTrackStep;
    _zoomTrack.onmouseup = zoomTrackStop;
    //_zoomTrack.onmouseout = zoomTrackStop;

    disableSelection(_zoomThumb);
    disableSelection(_zoomTrack);
    disableSelection(_zoomSmallerButton);
    disableSelection(_zoomLargerButton);

    zoomDisplay(true);
}

function disableSelection(element) 
{
    element.onselectstart = function() {
        return false;
    };
    element.unselectable = "on";
    element.style.MozUserSelect = "none";
    element.style.cursor = "default";
}

function zoomButtonStart(dir)
{
    zoomButtonStop();

    zoomButtonStep(dir);

    _zoomTimer = setInterval('zoomButtonStep(' + dir + ');', 50);
}

function zoomButtonStop() 
{
    if (_zoomTimer) {
        clearInterval(_zoomTimer);
        _zoomTimer = null;
    }
}

function zoomButtonStep(dir)
{
    _zoomZ = _zoomZ + dir * .05;

    if (_zoomZ < 0.0)
        _zoomZ = 0.0;

    if (_zoomZ > 1.0)
        _zoomZ = 1.0;

    zoomDisplay(true);
}

function zoomTrackStart(e)
{
    if (window.event)
        e = window.event;

    var x = e.clientX - getAbsolutePosition(_zoomThumb).x;
    if (x < 0)
        return;

    var w = getDivW(_zoomThumb);
    if (x > w)
        return;

    _zoomTrackDrag = true;
    _zoomTrackDragX = x;
}

function zoomTrackStop()
{
    _zoomTrackDrag = false;
}

function zoomTrackStep(e)
{
    if (window.event)
        e = window.event;

    if (!_zoomTrackDrag)
        return;

    var x = e.clientX - getAbsolutePosition(_zoomTrack).x - _zoomTrackDragX;

    if (x < _zoomThumbXMin)
        x = _zoomThumbXMin;

    if (x > _zoomThumbXMax)
        x = _zoomThumbXMax;

    _zoomThumb.style.left = x + 'px';

    _zoomZ = (x - _zoomThumbXMin) / (_zoomThumbXMax - _zoomThumbXMin);

    zoomDisplay(false);
}

function zoomDisplay(setThumb)
{
    if (setThumb)
        _zoomThumb.style.left = ((_zoomThumbXMax - _zoomThumbXMin) * _zoomZ + _zoomThumbXMin) + 'px';

    var w = _zoomZ * (_zoomWMax - _zoomWMin) + _zoomWMin;
    var h = w * _zoomRatio;

    var x;
    if (w <= _zoomWindowWidth) {
        x = (_zoomWindowWidth - w) / 2;
    }
    else {
        x = (_zoomWindowWidth - w) * _zoomX;
    }

    var y;
    if (h <= _zoomWindowHeight) {
        y = (_zoomWindowHeight - h) / 2;
    }
    else {
        y = (_zoomWindowHeight - h) * _zoomY;
    }

    _zoomImage.style.width = w + 'px';
    _zoomImage.style.height = h + 'px';
    _zoomImage.style.left = x + 'px';
    _zoomImage.style.top = y + 'px';

    //alert(_zoomImage.style.width);
}

function zoomWindowMove(e) 
{
    if (window.event)
        e = window.event;

    if (_zoomWindowWidth <= 0 || _zoomWindowHeight <= 0)
        return;

    //console.log(e.clientY + ' - ' + getAbsolutePosition(_zoomWindow).y);

    var x = e.clientX - getAbsolutePosition(_zoomWindow).x;
    var y = e.clientY - getAbsolutePosition(_zoomWindow).y;

    _zoomX = x / _zoomWindowWidth;

    if (_zoomX < 0.0)
        _zoomX = 0.0;

    if (_zoomX > 1.0)
        _zoomX = 1.0;

    _zoomY = y / _zoomWindowHeight;

    if (_zoomY < 0.0)
        _zoomY = 0.0;

    if (_zoomY > 1.0)
        _zoomY = 1.0;

    zoomDisplay(false);
}

function divLoading(id, webroot)
{
    var div = document.getElementById(id);
    if (div)
        div.innerHTML = '<div style="padding:5px; text-align:center;"><img src="' + webroot + '/images/loader.gif" /></div>';
}

// ALBUM SELECTOR
//

var _selectorT = null;
var _selectorC = null;
var _selectorCW = null;
var _selectorLW = null;
var _selectorI = null;
var _selectorM = null;
var _selectorCX = null;
var _selectorTX = null;

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 selectorInit(index) {
    // Get objects
    var table = document.getElementById('selectorTable');
    if (!table)
        return;

    var container = document.getElementById('selectorContainer');
    if (!container)
        return;

    var containerW = getDivW(container);

    // Pre-calculate table positions for every cell
    // and wire click events
    var i;
    var j;
    var a = 0;
    var x = 0;
    var cells = new Array();
    var cellWidths = new Array();
    for (i = 0; i < table.rows.length; i++) {
        var row = table.rows[i];
        for (j = 0; j < row.cells.length; j++) {
            var cell = row.cells[j];
            var cellW = getDivW(cell);

            cells[a] = cell;
            cellWidths[a] = forceInt(-(x + (cellW / 2)) + (containerW / 2));

            x += cellW;
            a++;
        }
    }

    // Cancel if no cells are found
    if (!cellWidths.length)
        return;

    // Set default values
    _selectorT = table;
    _selectorC = cells;
    _selectorCW = containerW;
    _selectorLW = cellWidths;
    _selectorI = 0;
    _selectorM = false;
    _selectorCX = _selectorLW[index || 0];
    _selectorTX = _selectorCX;

    // Move to first frame
    selectorMoveTo(index || 0);

    // Display table
    _selectorT.style.visibility = 'visible';
}

function selectorLeft() {
    selectorMoveTo(_selectorI - 1);
}

function selectorRight() {
    selectorMoveTo(_selectorI + 1);
}

function selectorMoveTo(index) {
    if (!_selectorT)
        return;

    // Enforce index limit
    if (index < 0)
        index = _selectorLW.length - 1;

    if (index > _selectorLW.length - 1)
        index = 0;

    // Un-highlight previous cell
    var cell = _selectorC[_selectorI];
    cell.style.backgroundColor = '';

    // Select new cell
    _selectorI = index;
    _selectorTX = _selectorLW[_selectorI];

    // Highlight new cell
    cell = _selectorC[_selectorI];
    cell.style.backgroundColor = '#EFF3E0';

    // Start animation, if necessary
    if (!_selectorM) {
        _selectorM = true;
        selectorMove();
    }
}

function selectorMove() {
    // Calculate frame distance
    var diff = forceInt(Math.abs(_selectorCX - _selectorTX) / 4) || 1;

    // Apply animation
    if (_selectorCX < _selectorTX) {
        _selectorCX += diff;
    }
    else if (_selectorCX > _selectorTX) {
        _selectorCX -= diff;
    }

    _selectorT.style.left = _selectorCX + 'px';

    // Schedule next frame, if necessary
    if (_selectorCX != _selectorTX) {
        setTimeout('selectorMove()', 40);
    }
    else {
        _selectorM = false;
    }
}

function extractParamFromUri(uri, paramName) {
    if (!uri) {
        return;
    }
    var uri = uri.split('#')[0];  // Remove anchor.
    var parts = uri.split('?');  // Check for query params.
    if (parts.length == 1) {
        return;
    }
    var query = decodeURI(parts[1]);

    // Find url param.
    paramName += '=';
    var params = query.split('&');
    for (var i = 0, param; param = params[i]; ++i) {
        if (param.indexOf(paramName) === 0) {
            return unescape(param.split('=')[1]);
        }
    }
}
