var Doc = {

    GetNamedElements : function (elementName) {
        return document.getElementsByName(elementName);
    },

    GetNamedElement: function (elementName) {
        return this.GetNamedElements(elementName)[0];
    },

    GetElement :  function (elementId) {
        return document.getElementById(elementId);
    },

    GetListElements : function (listId) {
        var list = this.GetElement(listId);
        return list.getElementsByTagName("LI");  
    },

    ShowElem: function (elementId, display) {
        if (!display) { display="block" }
        this.SetElemDisplay(elementId, display)
    },

    HideElem : function (elementId) {
        this.SetElemDisplay(elementId, "none")

    },

    ToggleElemDisplay: function (elementId, showDisplay) {

        var elem = Doc.GetElement(elementId);
        var newDisplay;
        if (elem) {
            var currentDisplay = elem.style.display;
            if (currentDisplay == "none")  
            {
                if (showDisplay) {
                    newDisplay = showDisplay
                } else {
                    newDisplay= "block"
                }
            } else { newDisplay="none"}
            elem.style.display = newDisplay;
        }
    
    },

    SetElemDisplay: function (elementId, display) {

        var elem = Doc.GetElement(elementId);
        if (elem) {
            elem.style.display = display
        }
    },

    SetElemHTML: function(elementId, htmlString) {
        var elem = Doc.GetElement(elementId);
        if (elem) {
            elem.innerHTML = htmlString;
        }
    },

    SetElemValue: function(elementId, value) {
        var elem = Doc.GetElement(elementId);
        if (elem) {
            elem.value = value;
        }
    }

};

function parseUri(sourceUri){
    var uriPartNames = ["source","protocol","authority","domain","port","path","directoryPath","fileName","query","anchor"];
    var uriParts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)?((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(sourceUri);
    var uri = {};
    
    for(var i = 0; i < 10; i++){
        uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : "");
    }
    
    // Always end directoryPath with a trailing backslash if a path was present in the source URI
    // Note that a trailing backslash is NOT automatically inserted within or appended to the "path" key
    if(uri.directoryPath.length > 0){
        uri.directoryPath = uri.directoryPath.replace(/\/?$/, "/");
    }
    
    return uri;
}

function NavigateTo(url) {
    var uriData = parseUri(url);
    if (window.location.protocol == uriData.protocol+":" &&
        window.location.pathname == uriData.path &&
        window.location.host == uriData.authority &&
        window.location.search == uriData.query)
    {
        window.location.href = url;
        window.location.reload(true);
    } else {
        window.location.href = url;
    }

}


function ShowStatus(msg) {
    
    window.status=msg;
}


function CalcRandom() {
    var retVal = Math.floor(Math.random() * 1001);
    return retVal;
}

function CheckExpired() {
    var request = CreateXmlHttpRequest();
    request.open("GET", "/check_expired?rand=" + CalcRandom(), true);
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                // Still active
                ;
            } else if (request.status == 403) {
                if (window.location.href == request.responseText) {
                    window.location.hash = "#popups=logged_out";
                    window.location.reload();
                } else {
                    // Nope, we're dead, close all active popups and say that we've been logged out
                    window.location.href = request.responseText + "#popups=logged_out";
                }
            }
        }
    }
    request.setRequestHeader("Cookie", "");
    request.send(null);
}


function IndexOfArrayElement (array, object) {
//    if (array.indexOf) {
//        return array.indexOf(object);
//    }
    for (var i = 0, length = array.length; i < length; i++) {
        if (array[i] == object) return i;}
    return -1;
}


function RemoveArrayElement(array, object) {
    var index = IndexOfArrayElement(array, object);
    if (index == -1) {
        return;
    } else {
        array.splice(index, 1);
    }
}


function ArrayHasElement(array, object) {
    return IndexOfArrayElement(array, object) > -1;
}

function ConcatObjects(object1, object2) {
    var newObject = object1;

    for (var key in object2) {
        newObject[key] = object2[key]
    
    }
    return newObject

}


/* Used for substituing variable name
*  place holders for variable values
* in Routing style urls
*/
function UrlSub(url, keyword, value) {
    newUrl = url.replace(":" + keyword, value);
    return newUrl;
}

function UrlSubs(url, keywords, values) {
    var newUrl = url;
    for (var i=0;i<keywords.length; i++) {
        keyword = keywords[i]
        value = values[i]
        newUrl = newUrl.replace(":" + keyword, value);
    }
    return newUrl;
}


var SiteSearch = {
    filterSection: "everywhere",
    timeoutId: null,
    kMenuTimeout: 2000,

    _FixSections: function () {
        var searchSections = ["everywhere", "photography", "illustration", "thedatabase"]

        for (var i=0; i<searchSections.length; ++i) {
            var link = document.getElementById("ss_" + searchSections[i]);
            if (link) {
                if (this.filterSection == searchSections[i]) {
                    link.className = "selected";
                } else {
                    link.className = "";
                }
            }
        }
    },

    ToggleSectionPopup: function () {
        var sectionPopup = document.getElementById("searchFloat");

        this._FixSections();

        if (sectionPopup) {
            if (sectionPopup.style.display == "block") {
                this.StopTimeout();
                sectionPopup.style.display = "none";
            } else {
                // this.StartTimeout();
                sectionPopup.style.display = "block";
            }
        }
    },

    ClosePopup: function () {
        this.timeoutId = null;
        var sectionPopup = document.getElementById("searchFloat");
        sectionPopup.style.display = "none";
    },

    StartTimeout: function () {
        this.timeoutId = setTimeout(this.ClosePopup, this.kMenuTimeout);
    },

    StopTimeout: function () {
        if (this.timeoutId != null) {
            clearTimeout(this.timeoutId);
            this.timeoutId = null;
        }
    },

    ResetTimeout: function () {
        clearTimeout(this.timeoutId);
        this.timeoutId = setTimeout(this.ClosePopup, this.kMenuTimeout);
    },

    CancelPopup: function () {
        this.StopTimeout();
        this.ClosePopup();
    },

    ClearSearch: function () {
        var searchText = document.getElementById("searchText").value;
        if (searchText == "enter name") {
            document.getElementById("searchText").value = "";
        }
    },

    FillSearch: function () {
        var searchText = document.getElementById("searchText").value;
        if (searchText == "") {
            document.getElementById("searchText").value = "enter name";
        }
    },

    SetSection: function (section) {
        this.filterSection = section;
        this._FixSections();
        this.StopTimeout();
        
        /* Hide the popup */
        var sectionPopup = document.getElementById("searchFloat");
        sectionPopup.style.display = "none";
    },

    SetSectionAndSubmit: function (section) {
        this.SetSection(section);
        var searchText = document.getElementById("searchText").value;
        if (searchText != "" && searchText != "enter name") {
            this.Search();
        }
    },

    Search: function () {
        this.StopTimeout();
        var searchText = document.getElementById("searchText").value;
        if (searchText != "") {
            PopupWindow.Register('siteSearch', {
                url: "/search?section=" + escape(this.filterSection) + "&text=" + escape(searchText),
                isDialog: true,
                fixTimeout: 20000
            });

            PopupWindow.CreateRegistered('siteSearch');
        }
    },

    KeyPress: function (event) {
        event = Events.FixEvent(event);
        var key;
        if (event.keyCode) {
            key = event.keyCode;
        } else if (event.which) {
            key = event.which;
        }
        if (key == 13) {
            SiteSearch.Search();
            event.cancelBubble = true;
            if (event.stopPropagation) event.stopPropagation();
            if (event.preventDefault) event.preventDefault();
            return false;
        } else {
            return true;
        }
    }
};


function FakeButtonSubmit(id, value) {
    var button = document.getElementById(id);
    var parent = button?button.parentNode:null;
    var form = null;

    while (parent) {
        if (parent.nodeType == 1 && parent.nodeName.toLowerCase() == "form") {
            form = parent;
            break;
        } else {
            parent = parent.parentNode;
        }
    }

    if (form) {
        var hiddenInput = null;

        if (button.name) {
            // Handle the bizarre case of submit buttons with values
            hiddenInput = document.createElement("input");
            hiddenInput.type = "hidden";
            hiddenInput.name = button.name;
            hiddenInput.value = value;
            form.appendChild(hiddenInput);
        }

        form.submit();

        if (hiddenInput) {
            form.removeChild(hiddenInput);
        }
    }
}

function Ellipsize(str, limit) {
    if (str.length < limit) {
        return str
    } else {
        return str.slice(0, limit) + "...";
    }
}


function GetParentForm(elem) {
    var result = elem.parentNode;
    while (result) {
        if (result.nodeType == 1 && result.nodeName.toLowerCase() == "form") {
            return result;
        } else {
            result = result.parentNode;
        }
    }
    return null;
}


var gPendingButtons = {};

function IsFancyButtonEnabled(btn)
{
    var elem = (typeof btn === "string")?document.getElementById(btn):btn;
    if (elem) {
        return elem.className === "btnSubmit" || elem.className === "btnReset";
    } else {
        return false;
    }
}

function DisableFancyButton(btn)
{
    var elem = (typeof btn === "string")?document.getElementById(btn):btn;
    if (elem) {
        if (IsFancyButtonEnabled(elem)) {
            elem.className = (elem.className === "btnSubmit")?"btnSubmitInactive":"btnResetInactive";
            gPendingButtons[elem.id] = elem.href;
            elem.href = "javascript:void(0)";
        }
    }
}

function EnableFancyButton(btn)
{
    var elem = (typeof btn === "string")?document.getElementById(btn):btn;
    if (elem) {
        if (!IsFancyButtonEnabled(elem)) {
            elem.href = gPendingButtons[elem.id];
            delete gPendingButtons[elem.id];
            elem.className = (elem.className == "btnSubmitInactive")?"btnSubmit":"btnReset";
        }
    }
}
