function forceInt(x, y)
{
	return isNaN(y = parseInt(x))? 0 : y;
}

function getDivW(el)
{
    var w = el ? (el.offsetWidth || el.style.pixelWidth || el.style.width || el.clientWidth || 0) : 0;
	return forceInt(w);
}

function getDivH(el)
{
    var h = el ? (el.offsetHeight || el.style.pixelHeight || el.style.height || el.clientHeight || 0) : 0;
	return forceInt(h);
}

function nodeValue(node)
{
    return (node.firstChild == null) ? '' : node.firstChild.nodeValue;
}

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 centerDivRelativeH(div, parentDiv)
{
    var d = document.getElementById(div);
    var p = document.getElementById(parentDiv);
        
    var dWidth = getDivWR(d);
    var pWidth = getDivWR(p);
    
    var offset = (pWidth - dWidth) / 2;
    d.style.left = offset + "px";
    d.style.width = dWidth + "px";
}

function centerDivRelativeV(div, parentDiv)
{
    var d = document.getElementById(div);
    var p = document.getElementById(parentDiv);
        
    var dHeight = getDivHR(d);
    var pHeight = getDivHR(p);
        
    var offset = (pHeight - dHeight) / 2;
    d.style.top = offset + "px";
    d.style.height = dHeight + "px";
}

var centerCacheH = new Array();
var centerCacheV = new Array();

function getDivWR(el)
{        
    var id = el.id;
    
    if (centerCacheH[id])
        return centerCacheH[id];

    var maxW = 0;
    
    for(var i = 0; i < el.childNodes.length; i++)
    {
        var child = el.childNodes[i];
        if (child && child.style)
        {
            maxW = Math.max(maxW, getDivW(child));
        }
    }
    
    centerCacheH[id] = maxW;
    return maxW;
}

function getDivHR(el)
{
    var id = el.id;
    
    if (centerCacheV[id])
        return centerCacheV[id];

    var maxH = 0;
    for(var i = 0; i < el.childNodes.length; i++)
    {
        var child = el.childNodes[i];
        if (child && child.style)
        {
            maxH = Math.max(maxH, getDivH(child));
        }
    }

    centerCacheV[id] = maxH;
    return maxH;
}

// 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) == '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();
}

function popupImage(url, width, height)
{
    popup(url, width, height, 'img', false);
}

// 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);
}

// 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 searchFocus(f)
{
    if (f.value == f.title)
    {
        f.value = '';
    }
}

function searchBlur(f)
{
    if (f.value == '')
    {
        f.value = f.title;
    }
}

function returnFromPopup(url)
{
    window.opener.refreshPage(url);
    window.close();
}

function refreshPage(url)
{
    window.focus();
    if(url == null)
      window.location.replace(window.location.href);
    else
      window.location.replace(url);
}

function returnFromRightContentPopup(refresh, id)
{
    if(refresh == 'true')
    {
      window.opener.refreshRightContent(id);
    }
    window.close();
}

// 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);
}

////////////////////////////////////////////////////////////////////
// GOOGLE MAPS
////////////////////////////////////////////////////////////////////

var map = null;

function isPrintView()
{
    var div = document.getElementById("printwrapper");
    return div != null;
}

function initGoogleMap(map_div)
{
    if (GBrowserIsCompatible()) 
    {
        var div = document.getElementById(map_div);
        if (div != null)
        {
            map = new GMap2(div);
            //map.setCenter(new GLatLng(38.5070010, -95.6379010), 4);
            map.enableScrollWheelZoom();

            if (!isPrintView())
            {
                map.addControl(new GLargeMapControl());
                map.addControl(new GMapTypeControl());
                map.enableInfoWindow();
            }
        }
    }
}

function getLocations(searchUrl)
{   
    if (map != null)
    {
        map.clearOverlays();            
        GDownloadUrl(searchUrl, function (data, responseCode) { populateMap(data, responseCode); });            
    }  
}

function populateMap(data, responseCode)
{
    if (responseCode == 200)
    {
        var locations = getLocationsFromXML(data);
        var entries = getEntriesFromLocations(locations);                
        
        if (entries.length > 0)        
        {   // Results were found            
            var bounds = new GLatLngBounds();
            
            for(var i in entries)
            {
                var entry = entries[i];                
                var marker = entry.marker;                    
       
                // Update bounds
                bounds.extend(marker.getLatLng());                
                // Add marker to map
                map.addOverlay(marker);
            }
            map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
        }
  
        if(typeof onMapLoadComplete == 'function') 
        {
            onMapLoadComplete();
        }
    }
}

function getEntriesFromLocations(locations)
{
    var entries = new Array();
    
    for (var i = 0; i < locations.length; i++)
    {
        var id = locations[i].getAttribute('id');
        var name = locations[i].getAttribute('name');
        var address = locations[i].getAttribute('address');
        var city = locations[i].getAttribute('city');
        var state = locations[i].getAttribute('state');
        var zip = locations[i].getAttribute('zip');
        var phone = locations[i].getAttribute('phone');                        
        var distance = parseFloat(locations[i].getAttribute('distance'));
        var icon = locations[i].getAttribute('icon');
        var email = locations[i].getAttribute('email');
        var latitude = parseFloat(locations[i].getAttribute('latitude'));
        var longitude = parseFloat(locations[i].getAttribute('longitude'));

        var point = new GLatLng(latitude, longitude);            
        var marker = createMarker(point, id, name, icon, address, city, state, zip, phone, email);
        
        
        var entry = new Object();
        entry.marker = marker;

        entries.push(entry);
    }
    
    return entries;
}
    
function getLocationsFromXML(data)
{
    var xml = GXml.parse(data);
    return xml.documentElement.getElementsByTagName('location');
}
        
function createMarker(point, id, name, icon, address, city, state, zip, phone, email)
{   // Create our custom marker
    var markerIcon = new GIcon();
    if (icon != null)
    {
        markerIcon.image = icon;
        markerIcon.printImage = icon;
        markerIcon.mozPrintImage = icon;
    }

    markerIcon.iconSize = new GSize(15, 23);
    markerIcon.iconAnchor = new GPoint(8, 23);
    markerIcon.infoWindowAnchor = new GPoint(8, 23); 
    markerIcon.shadow = WEB_ROOT + '/Images/map/shadow.png';
    markerIcon.shadowSize = new GSize(27,23);
    markerIcon.shadowAnchor = new GPoint(10,23);

    var markerOptions = { icon:markerIcon, title:name };
    var marker = new GMarker(point, markerOptions);
        
    if (!isPrintView())
    {
        // create balloon info
        var balloonInfo = createMarkerBalloonInfo(id, name, icon, address, city, state, zip, phone, email);

        var div = document.getElementById("sidebar." + id);
        if (div != null)
        {
            // Link div click event to marker        
            GEvent.addDomListener(div, 'click', function() { GEvent.trigger(marker, 'click'); });        

            // Add balloon info to marker            
            GEvent.addListener(marker, 'click', function() { marker.openInfoWindow(balloonInfo); div.scrollIntoView(true)});
        }
        else        
        {
            GEvent.addListener(marker, 'click', function() { marker.openInfoWindow(balloonInfo); });
        }
    }
    
    return marker;
}

function createMarkerBalloonInfo(id, name, icon, address, city, state, zip, phone, email)
{   // Create marker balloon info
    
    // retrieve the div containing item template
    var templateDiv = document.getElementById("balloonInfoTemplate");
    var template = templateDiv.innerHTML;
    
    // perform replacements on template
    template = template.replace("{id}", id);
    template = template.replace("{name}", name);
    template = template.replace("{address}", address);
    template = template.replace("{city}", city);
    template = template.replace("{state}", state);
    template = template.replace("{zip}", zip);
    template = template.replace("{phone}", phone);
    template = template.replace("{link}", "<a href='LocationDetail.aspx?id=" + id + "'>Select This Location</a>");
    template = template.replace("{email}", email);
    var div = document.createElement("div");
    div.innerHTML = template;
    return div;        
}

function notAuthenticated(url)
{
    var parent = window;
    while (parent.opener != null)
    {
      parent.close();
      parent = parent.opener;
    }
    parent.refreshPage(url);
}
