var selectedRow = null;
var curId = 0;
var curXmlRequest = null;

if (typeof xmlrequest == "undefined") var xmlrequest = new Object();
xmlrequest.AjaxRequest = function(uri, container, callback)
{
    this.uri = uri;
    this.container = container;
    this.callback = callback;
    this.cancelled = false;
    this.xmlHttp = null;

    try
    {
        // Firefox, Opera 8.0+, Safari
        this.xmlHttp = new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try
        {
            this.xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                this.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e)
            {
                this.xmlHttp = null;
            }
        }

    }

    var readyStateProcess = this.processXml;
    var ajaxObj = this;
    this.xmlHttp.onreadystatechange = function()
    {
        readyStateProcess(ajaxObj);
    };
}

xmlrequest.AjaxRequest.prototype = {
    cancel: function()
    {
        this.cancelled = true;
    },

    isCancelled: function()
    {
        return this.cancelled;
    },

    getXmlHttp: function()
    {
        return this.xmlHttp;
    },

    doGet: function()
    {
        this.xmlHttp.open("GET", this.uri, true);
        this.xmlHttp.send(null);
    },

    doPost: function(params)
    {
        try
        {
            this.xmlHttp.open("POST", this.uri, true);
            this.xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            this.xmlHttp.setRequestHeader("Content-Length", params.length);
            this.xmlHttp.setRequestHeader("Connection", "close");
            this.xmlHttp.send(params);
        }
        catch(e)
        {
            alert(e);
        }
    },

    processXml: function(ajaxReqObj)
    {
        if (ajaxReqObj.xmlHttp.readyState == 4)
        {
            if (ajaxReqObj.xmlHttp.status == 200)
            {
                if (! ajaxReqObj.isCancelled())
                {
                    var html = ajaxReqObj.xmlHttp.responseText;
                    updateLoginStatus(ajaxReqObj.xmlHttp);

                    if (ajaxReqObj.callback != null)
                    {
                        ajaxReqObj.callback(ajaxReqObj.uri, ajaxReqObj.container, html);
                    }
                    else
                    {
                        alert(html);
                    }
                }
            }
            else
            {
                alert("Error loading content (" + ajaxReqObj.xmlHttp.status + "). Refresh your browser and try again.");
            }
        }
    }
}

function loadContainer(uri, container, callback, displayStatus)
{
    if (curXmlRequest != null)
    {
        curXmlRequest.cancel();
    }

    var xmlRequest = curXmlRequest = new xmlrequest.AjaxRequest(uri, container, callback);
    var xmlHttp = xmlRequest.getXmlHttp();
    if (xmlHttp == null)
    {
        return;
    }
    if (displayStatus == null || displayStatus)
    {
        showLoading(container);
    }

    xmlRequest.doGet(uri);
}

function onLoadContainer(uri, container, html)
{
    container.innerHTML = html;
    checkJsCommand(html, container);
    analytics.load(uri);
}

function onSubmitForm(element, container)
{
    if (container == null)
    {
        container = getLeftContainer();
    }
    return submitForm(element, container, onLoadContainer);
}


function submitForm(element, container, callback, displayStatus)
{
    var theForm = element;

    while (theForm != null && theForm.tagName != "FORM")
    {
        theForm = theForm.parentNode;
    }
    if (theForm == null)
    {
        return false;
    }

    var params = "";
    var input;
    for (var i = 0; i < theForm.length; i++)
    {
        if (i > 0)
        {
            params += "&";
        }
        input = theForm.elements[i];
        if (input.type == "checkbox")
        {
            if (input.checked)
            {
                params += input.name + "=" + encodeURIComponent(input.value);
            }
        }
        else
        {
            params += input.name + "=" + encodeURIComponent(input.value);
        }
    }
    params += "&" + element.name + ".x=0";

    if (curXmlRequest != null)
    {
        curXmlRequest.cancel();
    }

    var xmlRequest = curXmlRequest = new xmlrequest.AjaxRequest(theForm.action, container, callback);
    var xmlHttp = xmlRequest.getXmlHttp();
    if (xmlHttp == null)
    {
        return false;
    }

    selectedRow = null;
    curId = 0;

    if (displayStatus == null || displayStatus)
    {
        showLoading(container);
    }

    xmlRequest.doPost(params);
    return false;
}


function displayHtmlPopup(uri)
{
    var ajaxRequest = new xmlrequest.AjaxRequest(uri, null, function(a, b, html)
{
    grayPopup(true, html);
});
    ajaxRequest.doGet();
}

function openPopup(url, name, w, h)
{
    window.open(url, name, 'width=' + w + ', height=' + h +
                                'location=no, menubar=no, status=yes, toolbar=no, scrollbars=yes, resizable=no, directories=no');
}

function openWindow(url, name, w, h)
{
    if (name == null)
    {
        name = "";
    }

    var props = "location=yes, menubar=yes, status=yes, toolbar=yes, scrollbars=yes, resizable=yes, directories=yes";
    if (w != null)
    {
        props += ",width=" + w;
    }
    if (h != null)
    {
        props += ",height=" + h;
    }

    window.open(url, name, props);
}

function onSelectContent(url)
{
    loadLeftContainer(url);
}


function checkJsCommand(html, container)
{
    if (html.indexOf("jsCommand") == -1)
    {
        return;
    }

    var script = "";
    var js = document.getElementById("jsCommand");
    if (js != null)
    {
        script = js.innerHTML;
        html = html.replace("jsCommand", "");
        container.innerHTML = html;
        eval(script);
    }
}


function getRightContainer()
{
    return getContainer("rightContent");
}

function getFormContainer()
{
    return getContainer("formContent");
}

function getLeftContainer()
{
    return getContainer("leftContent");
}

function getContainer(id)
{
    return document.getElementById(id)
}


function loadFormContainer(uri, displayStatus, callback)
{
    var leftContent = getLeftContainer();
    leftContent.style.display = "none";

    var formContent = getFormContainer();
    loadContainer(uri, formContent, callback, displayStatus);
    formContent.style.display = "block";
}

function hideFormContainer()
{
    var formContent = getFormContainer();
    formContent.style.display = "none";

    var leftContent = getLeftContainer();
    leftContent.style.display = "block";
}

function loadLeftContainer(uri, displayStatus, callback)
{
    callback = (callback == null ? onLoadContainer : callback);
    hideFormContainer();
    loadContainer(uri, getLeftContainer(), callback, displayStatus);
}

function loadRightContainer(uri)
{
    loadContainer(uri, getRightContainer(), onLoadContainer);
}

function showLoading(container)
{
    container.innerHTML = "<div style=\"padding-top:10px;\">" +
                          "<img src=\"/images/template/circle_ball.gif\" height=\"32\" width=\"32\">" +
                          "</div>";
}

function removeTableRow(tableRow)
{
    var rowIndex = tableRow.rowIndex;
    var element = tableRow;

    while (element != null && element.tagName != "TABLE")
    {
        element = element.parentNode;
    }
    if (element != null)
    {
        element.deleteRow(rowIndex);
    }
}

//function recordRemovedEvent()
//{
//    mainToolbar.removeSelectedRecord();
//    hideFormContainer();
//}
//
//
function onSortRecords(columnIndex)
{
    var columnField = document.getElementsByName("sortColumn")[0];
    var oldIndex = columnField.value;
    columnField.value = columnIndex;

    var sortField = document.getElementsByName("sortDirection")[0];
    if (oldIndex == "" || oldIndex != columnIndex)
    {
        sortField.value = 1;
    }
    else
    {
        if (sortField.value < 0)
        {
            columnField.value = "";
            sortField.value = "";
        }
        else
        {
            sortField.value = -1;
        }
        //        sortField.value = (sortField.value < 0) ? 1 : -1;
    }

    gotoPage(1);
}


function gotoPage(pageNumber)
{
    var field = document.getElementsByName("page")[0];
    field.value = pageNumber;
    loadListRecords(true);
}


function selectRecord(tableRow, id)
{
    if (selectedRow != null)
    {
        selectedOff(selectedRow);
    }
    selectedOn(tableRow);
    selectedRow = tableRow;

    curId = id;
}

function hiOn(row)
{
    if (! hasStyleClass(row, 'selected'))
    {
        addStyleClass(row, 'highlight');
    }
}

function hiOff(row)
{
    if (! hasStyleClass(row, 'selected'))
    {
        delStyleClass(row, 'highlight');
    }
}

function selectedOn(row)
{
    delStyleClass(row, 'highlight');

    if (! hasStyleClass(row, 'selected'))
    {
        addStyleClass(row, 'selected');
    }
}

function selectedOff(row)
{
    delStyleClass(row, 'selected');
    delStyleClass(row, 'highlight');
}


function hasStyleClass(elem, clazzName)
{
    var n = ' ' + elem.className + ' ';
    return (n.indexOf(' ' + clazzName + ' ') >= 0);
}

function addStyleClass(elem, clazzName)
{
    var n = ' ' + elem.className + ' ';
    if (n.indexOf(' ' + clazzName + ' ') < 0)
    {
        elem.className += (elem.className && elem.className.length > 0) ? ' ' + clazzName : clazzName;
    }
}

function delStyleClass(elem, clazzName)
{
    var n = ' ' + elem.className + ' ';

    var len = clazzName.length;
    var start = n.indexOf(' ' + clazzName + ' ');

    if (start >= 0)
    {
        var end = start + len + 1;
        elem.className = n.substring(0, start) + n.substring(end, n.length);
    }
}

function appendRedirectUrls(pageUrl, srcUrl, destUrl)
{
    if (srcUrl != null)
    {
        pageUrl = appendParameter(pageUrl, "srcUrl", srcUrl);
    }

    if (destUrl != null)
    {
        pageUrl = appendParameter(pageUrl, "destUrl", destUrl);
    }

    return pageUrl;
}


function appendParameter(url, parameterName, value)
{
    if (parameterName == null || parameterName == "")
    {
        return url;
    }

    url += (url.indexOf("?") == -1) ? "?" : "&";
    url += parameterName + "=" + value;
    return url;
}


function mailto(mailbox)
{
    window.location = "mailto:" + mailbox + "@bibleway.org";
}

// Changing style sheets
//function setActiveStyleSheet(title)
//{
//    var i, a, main;
//    for (i = 0; (a = document.getElementsByTagName("link")[i]); i++)
//    {
//        if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title"))
//        {
//            a.disabled = true;
//            if (a.getAttribute("title") == title) a.disabled = false;
//        }
//    }
//}
//
//function getActiveStyleSheet()
//{
//    var i, a;
//    for (i = 0; (a = document.getElementsByTagName("link")[i]); i++)
//    {
//        if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
//    }
//    return null;
//}
//
//function getPreferredStyleSheet()
//{
//    var i, a;
//    for (i = 0; (a = document.getElementsByTagName("link")[i]); i++)
//    {
//        if (a.getAttribute("rel").indexOf("style") != -1
//                && a.getAttribute("rel").indexOf("alt") == -1
//                && a.getAttribute("title")
//                ) return a.getAttribute("title");
//    }
//    return null;
//}
//
//function createCookie(name, value, days)
//{
//    if (days)
//    {
//        var date = new Date();
//        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
//        var expires = "; expires=" + date.toGMTString();
//    }
//    else expires = "";
//    document.cookie = name + "=" + value + expires + "; path=/";
//}
//
//function readCookie(name)
//{
//    var nameEQ = name + "=";
//    var ca = document.cookie.split(';');
//    for (var i = 0; i < ca.length; i++)
//    {
//        var c = ca[i];
//        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
//        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
//    }
//    return null;
//}
//
//window.onload = function(e)
//{
//    var cookie = readCookie("style");
//    var title = cookie ? cookie : getPreferredStyleSheet();
//    setActiveStyleSheet(title);
//}
//
//window.onunload = function(e)
//{
//    var title = getActiveStyleSheet();
//    createCookie("style", title, 365);
//}

//var cookie = readCookie("style");
//var title = cookie ? cookie : getPreferredStyleSheet();
//setActiveStyleSheet(title);

var analytics =
{
    load: function(uri)
    {
        if (analytics.isTrackingPage(uri))
        {
            try
            {
                pageTracker = _gat._getTracker(analytics.getTrackingNumber());
                pageTracker._initData();
                pageTracker._trackPageview(uri);
            }
            catch(err)
            {
                // Catch error in case _gat is undefined
            }
        }
    },

    isTrackingPage: function(uri)
    {
        return uri.indexOf("/admin/") == -1;
    },

    getHostName: function()
    {
        return window.location.hostname.toLowerCase();
    },

    getTrackingNumber: function()
    {
        var hostName = analytics.getHostName();
        switch (hostName)
                {
            case "www.biblebelievers.org":
            case "biblebelievers.org":
                return "UA-4538981-1";
            case "www.bibleway.org":
            case "bibleway.org":
                return "UA-4538981-2";
//            case "preview.bibleway.org":
//                return "UA-4538981-3";
            default:
                return "";
        }
    }
}

function grayPopup(vis, html){
   grayOut(vis);
   displayHtml(vis, html);
}

function grayOut(vis) {
  var dark=document.getElementById('darkScreen');
  if (!dark) {
     dark = document.createElement('div');
     dark.style.position = "absolute";
     dark.style.top = "0px";
     dark.style.left = "0px";
     dark.style.overflow = "hidden";
     dark.style.display = "none";
     dark.id = "darkScreen";

     document.getElementsByTagName("body")[0].appendChild(dark);
  }

//  hideDropDowns(vis);

  if (vis) {
    setOpacity(dark, 0.8);

    dark.style.zIndex = 50;
    dark.style.backgroundColor = "#000000";
    dark.style.width = getFullWidth() + "px";
    dark.style.height = getScreenHeight() + "px";
    dark.style.display = "block";
  }
  else{
     dark.style.display = "none";
  }
}

function hideDropDowns(vis){
   var dd = document.getElementsByTagName("select");

   if(!vis){
      for(x = 0; x < dd.length; x++){
         dd[x].style.display = dd[x].oldDisplay;
      }
   }
   else{
      for(x = 0; x < dd.length; x++){
         dd[x].oldDisplay = dd[x].style.display;
         dd[x].style.display = "none";
      }
   }
}

function setOpacity(obj, opacity){
   obj.style.opacity = opacity;
   obj.style.MozOpacity = opacity;
   obj.style.filter = "alpha(opacity=" + (opacity*100) + ")";
}

function getScreenHeight(){
	if (self.innerHeight)
		return self.innerHeight;
	else if (document.documentElement && document.documentElement.clientHeight)
		return document.documentElement.clientHeight;
	else if (document.body)
		return document.body.clientHeight;
}

function getScreenWidth(){
	if (self.innerWidth)
		return self.innerWidth;
	else if (document.documentElement && document.documentElement.clientWidth)
		return document.documentElement.clientWidth;
	else if (document.body)
		return document.body.clientWidth;
}

function getFullHeight(){
   var d = document.getElementsByTagName("body")[0];
   if(d.scrollHeight)
      return d.scrollHeight;
   else
      return d.offsetHeight;
}

function getFullWidth(){
   var d = document.getElementsByTagName("body")[0];
   if(d.scrollWidth)
      return d.scrollWidth;
   else
      return d.offsetWidth;
}
var keepAdjusting = false;
var adjustWait = 10;
var adjustTotalWait = 100; //10000;
var adjustCount = 0;

function adjustLocation(){
   var display = document.getElementById("displayPopup");
   var t = ((getScreenHeight() - display.offsetHeight)/2) + document.body.scrollTop;
   var l = ((getScreenWidth() - display.offsetWidth)/2) + document.body.scrollLeft;

   if(t < 0) t = 0;
   if(l < 0) l = 0;

   if(keepAdjusting && (adjustCount++*adjustWait)<adjustTotalWait){
	   display.style.top = t + "px";
	   display.style.left = l + "px";
       setTimeout("adjustLocation()",adjustWait);
   }
   else{
      keepAdjusting = false;
      adjustCount = 0;
   }
}

function displayHtml(vis, html){
   var display = document.getElementById("displayPopup");
   if(!display){
      display = document.createElement("div");
      display.style.position = "absolute";
      display.style.overflow = "hidden";
      display.style.display = "none";
      display.id = "displayPopup";

      document.getElementsByTagName("body")[0].appendChild(display);
   }

   keepAdjusting = vis;

   if(vis){
	   display.style.zIndex = 100;
	   display.style.backgroundColor = "#101010";
       display.style.className = "htmlPopup";
	   display.style.display = "block";

	   display.innerHTML = html;
	   adjustLocation();
	}
	else{
	   display.style.display = "none";
	   display.innerHTML = "";
	}
}


function showFocusRect(element)
{
    delStyleClass(element, 'blur');

    if (! hasStyleClass(element, 'focus'))
    {
        addStyleClass(element, 'focus');
    }
}

function hideFocusRect(element)
{
    delStyleClass(element, 'focus');

    if (! hasStyleClass(element, 'blur'))
    {
        addStyleClass(element, 'blur');
    }
}

function setPathFromFlash(path)
{
    window.location.hash = path;
    reloadMenuFromContentPath();
}