var ajaxMode = false;

var _history    = [''];
var _histPos    = 0; // History position

var pageNumber = 0;
var pagesCount = 1;

var noteWindow = '';
var bookmarkWindow = '';

function updateCursor()
{
    if (!document.body.style.cursor) {
        document.body.style.cursor = "wait";
    } else {
        document.body.style.cursor = "";
    }
    
    updateHistoryButtonsStatus();
}

function reloadUrl(scroll, wnd)
{
    try {
        if (typeof wnd == 'undefined' || wnd == 'undefined' || wnd == '') {
            wnd = top;
        }
        
        if (typeof scroll == 'undefined' || scroll == 'undefined' || scroll == '') {
            scroll = '';
        }
        
        if (ajaxMode) {
            openUrl(self.document.getElementById('current_url').value);
            return false;
        } else {
            if (wnd.document.getElementById('current_url')) {
                switch (scroll) {
                case 'note':
                    if (wnd.location.href.search('#userNote') == -1) {
                        wnd.location.href += '#userNote';
                    } else {
                        history.go(0);
                    }
                    wnd.location.reload();
                    break;
                default:
                    wnd.location.href = self.document.getElementById('current_url').value;
                }
            }
        }
    } catch (e) {
    }
}

function openUrl(url, bHistorySwitch)
{
    if (typeof(forceRedirect) != 'undefined' && forceRedirect != '') {
        top.location.href = forceRedirect;
        
        return false;
    }
    
    if (ajaxMode) {
        
        if (!bHistorySwitch) {
            
            if (_histPos < (_history.length - 1)) {
                while ((_history.length - 1) > _histPos) {
                    _history.pop();
                }
            }
            
            _history[_history.length] = url;
            ++_histPos;
        }
        
        //alert(_history.toString().replace(/,/gi, "\n\n") + "\n\nHistory Length: " + _history.length + "\n_histPos: " + _histPos);
        
        if (url.match('\\?')) {
            url += '&template_type=xml';
        } else {
            url += '?template_type=xml';
        }
        var ajaxRequest = new AjaxRequest(url);
        
        ajaxRequest.setPreRequest(updateCursor);
        ajaxRequest.setPostRequest(updateCursor);
        ajaxRequest.sendRequest();
        
        return false;
    } else {
        document.cookie = 'history=1';
        return true;
    }
}

function goBack()
{
    if (ajaxMode) {
        if (_history[_histPos - 1]) {
            openUrl(_history[--_histPos], true);
        }
    } else {
        window.history.back();
    }
}

function goForward()
{
    if (ajaxMode) {
        if (_history[_histPos + 1]) {
            openUrl(_history[++_histPos], true);
        }
    } else {
        window.history.forward();
    }
}

function updateHistoryButtonsStatus()
{
    if (document.getElementById('toolbarBtnBack') && document.getElementById('toolbarBtnForward')) {
        
        var lbtn = document.getElementById('toolbarBtnBack');
        var rbtn = document.getElementById('toolbarBtnForward');
        
        if (pageNumber == 0) {
            lbtn.className = 'btn_back_inactive';
            rbtn.className = '';
        } else if (pageNumber == pagesCount - 1) {
            lbtn.className = '';
            rbtn.className = 'btn_forward_inactive';
        } else {
            lbtn.className = '';
            rbtn.className = '';
        }
    }
}

function submitForm(form)
{
    if (ajaxMode) {
        var re = /\/[^\/]*$/gi
        var url = top.location.href.replace(re, '/');
        /*
        if (url.match('\\?')) {
            url += '&template_type=xml';
        } else {
            url += '?template_type=xml';
        }
        */
        var ajaxRequest = new AjaxRequest(url);
        //ajaxRequest.setUsePost();
        ajaxRequest.addFormElements(form);
        ajaxRequest.addNameValuePair('template_type', 'xml');
        //alert(ajaxRequest.queryString);return false;
        ajaxRequest.setPreRequest(updateCursor);
        ajaxRequest.setPostRequest(updateCursor);
        ajaxRequest.sendRequest();
        //ajaxRequest.setUseGet();
        return false;
    } else {
        return true;
    }
}

/*
function initialRedirect()
{
    if (top.location.href.match('#')) {
        openUrl(top.location.href)
    }
}
*/

function note(storage_id)
{
    if (typeof(forceRedirect) != 'undefined' && forceRedirect != '') {
        top.location.href = forceRedirect;
        
        return false;
    }
    
    var h = 360;
    var w = 500;
    
    /*if (window.showModalDialog && navigator.userAgent.match(/Firefox/)) {
        window.showModalDialog('?target=note&storage_id=' + storage_id,
            "note_edit",
            "dialogWidth:" + w + "px;dialogHeight:" + h + "px;");
    } else {*/
        if (window.location.href.match(/\/topics\/.*$/)) {
            noteWindow = window.open( window.location.href.replace(/\/topics\/.*$/, '/') +
                'index.php?target=note&storage_id=' + storage_id,
                'note_edit',
                'status=0,resizable=0,width=' + w + ',height=' + h + ',toolbar=0,location=0,' + 
                'left=' + ((screen.width - w) / 2) + ',top=' + ((screen.height - h) / 2) + ',' +
                'modal=yes');
        } else if (window.location.href.match(/\/help\/.*$/)) {
            noteWindow = window.open( window.location.href.replace(/\/help\/.*$/, '/') +
                'index.php?target=note&storage_id=' + storage_id,
                'note_edit',
                'status=0,resizable=0,width=' + w + ',height=' + h + ',toolbar=0,location=0,' + 
                'left=' + ((screen.width - w) / 2) + ',top=' + ((screen.height - h) / 2) + ',' +
                'modal=yes');
        } else {
            noteWindow = window.open('index.php?target=note&storage_id=' + storage_id,
                'note_edit',
                'status=0,resizable=0,width=' + w + ',height=' + h + ',toolbar=0,location=0,' + 
                'left=' + ((screen.width - w) / 2) + ',top=' + ((screen.height - h) / 2) + ',' +
                'modal=yes');
        }
        if (noteWindow == null) {
            alert('The popup window for this feature has been blocked. \nYou may need to add Alchemy to the trusted sites in your popup blocker.');
        } else {
            updateFocus();
        }
    //}
    
    return false;
}

function deleteNote(storage_id, return_url)
{
    if (confirm('Are you sure you want to delete the note?')) {
        if (ajaxMode) {
            var url = 'index.php?target=note&action=delete&storage_id=' + storage_id + '&returnUrl=' + escape(return_url) + '&template_type=xml';
            var ajaxRequest = new AjaxRequest(url);
            ajaxRequest.sendRequest();
        } else {
            top.location.href = 'index.php?target=note&action=delete&storage_id=' + storage_id + '&returnUrl=' + escape(return_url);
        }
    }
}

function clearHistory()
{
    if (confirm('Are you sure you want to clear the history?')) {
        if (ajaxMode) {
            var url = 'index.php?target=history&action=clear&template_type=xml';
            var ajaxRequest = new AjaxRequest(url);
            ajaxRequest.sendRequest();
        } else {
            top.location.href = 'index.php?target=history&action=clear';
        }
    }
}

function settingsClearHistory()
{
    if (confirm('Are you sure you want to clear the history?')) {
        if (ajaxMode) {
            var url = 'index.php?target=settings&action=clear_history&template_type=xml';
            var ajaxRequest = new AjaxRequest(url);
            ajaxRequest.sendRequest();
        } else {
            top.location.href = 'index.php?target=settings&action=clear_history';
        }
    }
}

function settingsClearBookmarks()
{
    if (confirm('Are you sure you want to delete all your bookmarks?')) {
        if (ajaxMode) {
            var url = 'index.php?target=settings&action=clear_bookmarks&template_type=xml';
            var ajaxRequest = new AjaxRequest(url);
            ajaxRequest.sendRequest();
        } else {
            top.location.href = 'index.php?target=settings&action=clear_bookmarks';
        }
    }
}

function settingsClearNotes()
{
    if (confirm('Are you sure you want to clear all your notes?')) {
        if (ajaxMode) {
            var url = 'index.php?target=settings&action=clear_notes&template_type=xml';
            var ajaxRequest = new AjaxRequest(url);
            ajaxRequest.sendRequest();
        } else {
            top.location.href = 'index.php?target=settings&action=clear_notes';
        }
    }
}

function bookmark(storage_id)
{
    if (typeof(forceRedirect) != 'undefined' && forceRedirect != '') {
        top.location.href = forceRedirect;
        
        return false;
    }
    
    var h = 270;
    var w = 600;
    bookmarkWindow = window.open(
        '?target=bookmark&storage_id=' + storage_id,
        'bookmark_edit',
        'status=no,resizable=0,width=' + w + ',height=' + h + ',toolbar=no,location=no,' + 
        'left=' + ((screen.width - w) / 2) + ',top=' + ((screen.height - h) / 2) + ',' +
        'modal=yes');
        
    if (bookmarkWindow == null) {
        alert('The popup window for this feature has been blocked. \nYou may need to add Alchemy to the trusted sites in your popup blocker.');
    } else {
        updateFocus();
    }
    
    return false;
}

function deleteBookmark(storage_id, return_url)
{
    if (confirm('Are you sure you want to delete the bookmark?')) {
        if (ajaxMode) {
            var url = 'index.php?target=bookmark&action=delete&storage_id=' + storage_id + '&returnUrl=' + escape(return_url) + '&template_type=xml';
            var ajaxRequest = new AjaxRequest(url);
            ajaxRequest.sendRequest();
        } else {
            top.location.href = 'index.php?target=bookmark&action=delete&storage_id=' + storage_id + '&returnUrl=' + escape(return_url);
        }
    }
}

function deleteAllBookmarks()
{
    if (confirm('Are you sure you want to delete all your bookmarks?')) {
        if (ajaxMode) {
            var url = 'index.php?target=bookmarks&action=delete_all&template_type=xml';
            var ajaxRequest = new AjaxRequest(url);
            ajaxRequest.sendRequest();
        } else {
            top.location.href = 'index.php?target=bookmarks&action=delete_all';
        }
        
        return true;
    }
}

function addCss(cssFile)
{
    if(document.createStyleSheet) {
        document.createStyleSheet(cssFile);
    } else {
        var styles = "@import url('" + cssFile + "');";
        var newSS=document.createElement('link');
        newSS.rel='stylesheet';
        newSS.href='data:text/css,'+escape(styles);
        document.getElementsByTagName("head")[0].appendChild(newSS);
    }
}

function isBrowser(browserName)
{
    switch (browserName) {
    case 'MSIE':
        return (navigator.appName=="Microsoft Internet Explorer");
    default:
        return true;
    }
}

function imgPreload()
{ 
    var i, args = imgPreload.arguments;
    
    document.preloadedImages = new Array(args.length);
    
    for(i = 0; i < args.length; ++i) {
        document.preloadedImages[i]     = new Image();
        document.preloadedImages[i].src = args[i];
    }
}

function updateFocus()
{
    if (noteWindow != null && noteWindow != '' && !noteWindow.closed && noteWindow.open) {
        noteWindow.focus();
    }
    
    if (bookmarkWindow != null && bookmarkWindow != '' && !bookmarkWindow.closed && bookmarkWindow.open) {
        bookmarkWindow.focus();
    }
}

function submitToS()
{
    if (document.getElementById('tos_confirm1').checked) {
        return true;
    }
    
    if (confirm("I agree to the Terms of use")) {
        document.getElementById('tos_confirm1').checked = true;
        document.getElementById('tos_confirm2').checked = true;
        return true;
    }
}

function deleteNoteFromEdit()
{
    if (confirm('Are you sure you want to delete the note?')) {
        document.forms['note_form'].action.value='delete';
        document.forms['note_form'].submit();
    }
}

