﻿
var g_msgErrorCommServer = 'An error occurred while trying to communicate with the server.';

var g_derivedId;
var g_tickers;
var g_curTickerIndex = 0;
var g_backToMyAccount = 0;

var fieldType = {
    AnyValue: 0,
    Email: 1,
    Password: 2,
    Price: 3
};

function isNiche() {
    return document.getElementById('IsNicheSite').innerHTML == '1' ? true : false;
}

function OnLoadComplete() {
    if (!isNiche()) {
        initializeTickers();
    }

    updateUserLoginState();
    amazonResults();
}

///////////////////////////////////////////////////////////
// Http Request
///////////////////////////////////////////////////////////
function createHttpRequest(url) {
    var instance;

    if (window.XMLHttpRequest) {
        instance = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        try {
            instance = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                instance = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) { }
        }
    }

    if (instance != null && url != null) {
        if (url.indexOf('?') == -1) {
            url = url + '?xr=' + Math.floor(Math.random() * 16384);
        } else {
            url = url + '&xr=' + Math.floor(Math.random() * 16384);
        }

        instance.open('GET', url, true);
    }

    return instance;
}

///////////////////////////////////////////////////////////
// Amazon
///////////////////////////////////////////////////////////
function amazonResults() {
    var section = document.getElementById('AmazonResultsUrl');
    if (section != null) {
        var url = trim(section.innerHTML);
        if (url != '') {
            request = createHttpRequest(url);
            request.onreadystatechange = function () {
                if (request.readyState == 4) {
                    if (request.status == 200) {
                        var panel = document.getElementById('AmazonResults');
                        panel.innerHTML = request.responseText;
                    } else {
                        var panel = document.getElementById('AmazonResults');
                        panel.innerHTML = 'Error occurred while trying to get Amazon results.';
                    }
                }
            }

            request.send(null);   
        }
    }
}

///////////////////////////////////////////////////////////
// Utl
///////////////////////////////////////////////////////////
function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds) {
            break;
        }
    }
}

function isspace(ch) {
    return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t';
}

function trim(buffer) {
    var output = '';
    var index = 0;
    var ch;

    for (index = 0; index < buffer.length && buffer.charAt(index) == ' '; index++);
    output = buffer.substr(index);

    if (output.length > 0) {
        index = output.length - 1;
        while (index > 0) {
            ch = output.charAt(index);
            if (isspace(ch) == false) {
                break;
            }

            index--;
        }

        output = output.substr(0, index + 1);
    }

    return output;
}

///////////////////////////////////////////////////////////
// Validation
///////////////////////////////////////////////////////////

function validateField(id, fldtype, errId, errMsg) {
    var value = document.getElementById(id).value;

    if (fldtype != fieldType.Password) {
        value = trim(value);
    }

    if (fldtype == fieldType.Email) {
        if (value.indexOf('@') == -1) {
            value = '';
        }
    } else if (fldtype == fieldType.Price) {
        if (isNaN(parseFloat(value))) {
            value = '';
        }
    }

    if (value.length == 0) {
        setErrorInPanel(errId, errMsg);
        value = null;
    }

    return value;
}

///////////////////////////////////////////////////////////
// Cookie Management
///////////////////////////////////////////////////////////
function setCookie(key, value, expiryDays) {
    var expires = '';
    var date = new Date();

    date.setTime(date.getTime() + (expiryDays * 24 * 60 * 60 * 1000));
    expires = date.toGMTString();
    document.cookie = key + '=' + value + '; expires=' + expires + '; path=/';
}

function getCookie(key) {
    var index;
    var endIndex;
    var value;

    key = key + '=';
    index = document.cookie.indexOf(key);
    if (index >= 0) {
        index += key.length;
        endIndex = document.cookie.indexOf(';', index);
        if (endIndex == -1) {
            endIndex = document.cookie.length - 1;
        } else {
            endIndex--;
        }

        value = document.cookie.substr(index, endIndex - index + 1);
    }

    return value;
}

///////////////////////////////////////////////////////////
// Ticker Management
///////////////////////////////////////////////////////////
function initializeTickers() {
    var tickers = document.getElementById('TopBar_Ticker_List').innerHTML;
    g_tickers = tickers.split('#');
    updateTickers();
}

function updateTickers() {
    document.getElementById('TopBar_Ticker').innerHTML = g_tickers[g_curTickerIndex];
    g_curTickerIndex += 1;
    if (g_curTickerIndex >= g_tickers.length) {
        g_curTickerIndex = 0;
    }

    setTimeout('updateTickers();', 2000);
}

///////////////////////////////////////////////////////////
// User Management
///////////////////////////////////////////////////////////

function IsWatched(list, name) {
    if (name.length < 12) {
        return false;
    }

    var did = name.substr(11);
    if (did.indexOf('_msg') > -1) {
        did = did.substr(0, did.length - 4);
    }

    var i;
    for (i = 0; i < list.length; i++) {
        if (did == list[i]) {
            return true;
        }
    }

    return false;
}

function enableTab(activeTab, pattern) {
    var regex = new RegExp(pattern);
    var all;
    var element;
    var i;

    if (document.all) {
        all = document.all;
    } else {
        all = document.getElementsByTagName('body')[0].getElementsByTagName('*');
    }

    for (i = 0; i < all.length; i++) {
        element = all[i];
        if (regex.test(element.id)) {
            if (element.id.length > activeTab.length && element.id.substr(0, activeTab.length) == activeTab) {
                if (element.id.indexOf('_Title') > -1) {
                    element.style.backgroundColor = '#ffffff';
                }
                else {
                    element.style.display = 'inline';
                }
            }
            else {
                if (element.id.indexOf('_Title') > -1) {
                    element.style.backgroundColor = '#f0f0f0';
                }
                else {
                    element.style.display = 'none';
                }
            }
        }
    }
}

function UpdateAlertOptions() {
    var list = document.getElementById('UserWatchList').innerHTML.split(',');
    var addRE = new RegExp('DivAddAlert*');
    var removeRE = new RegExp('DivDelAlert*');
    var user = getUser();
    var all;
    var element;
    var i;

    if (document.all) {
        all = document.all;
    } else {
        all = document.getElementsByTagName('body')[0].getElementsByTagName('*');
    }

    for (i = 0; i < all.length; i++) {
        element = all[i];

        if (addRE.test(element.id)) {
            if (user == null) {
                element.style.display = 'inline';
            }
            else if (IsWatched(list, element.id)) {
                element.style.display = 'none';
            }
            else {
                element.style.display = 'inline';
            }
        } else if (removeRE.test(element.id)) {
            if (user == null) {
                element.style.display = 'none';
            }
            else if (IsWatched(list, element.id)) {
                element.style.display = 'inline';
            }
            else {
                element.style.display = 'none';
            }
        }
    }
}


function updateUserLoginState() {

    if (getUser() == null) {
        document.getElementById('TopBar_Login').style.display = 'inline';
        document.getElementById('TopBar_LoggedIn').style.display = 'none';
    }
    else {
        document.getElementById('TopBar_Login').style.display = 'none';
        document.getElementById('TopBar_LoggedIn').style.display = 'inline';
        document.getElementById('TopBar_UserName').innerHTML = getCookie('UN');
    }

    UpdateAlertOptions();
}

function getUser() {
    var uid = getCookie('UID');
    var cid = getCookie('CID');
    var uname = getCookie('UN');
    var user;

    if (uid != null && cid != null && uname != null) {
        user = new Object();
        user.userid = uid;
        user.cid = cid;
        user.username = uname;
    }

    return user;
}

function logoutUser() {
    setCookie('UID', -1, -365);
    setCookie('CID', -1, -365);
    setCookie('UN', -1, -365);
    document.getElementById('UserWatchList').innerHTML = '';
    updateUserLoginState();
    closePanel();
}

function loginUser() {
    var password = validateField('LoginPanel_Password', fieldType.Password, 'LoginPanel_Status', 'Specify the password for the account.');
    var userName = validateField('LoginPanel_UserName', fieldType.AnyValue, 'LoginPanel_Status', 'Specify a valid user name.');
    var request;

    if (userName != null && password != null) {
        setWaitInPanel('LoginPanel_Status');
        request = createHttpRequest('/services/login.aspx?u=' + encodeURIComponent(userName) + '&p=' + encodeURIComponent(password));
        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                if (request.status == 200) {
                    processLoginResponse(request.responseText);
                } else {
                    setErrorInPanel('LoginPanel_Status', g_msgErrorCommServer);
                }
            }
        }

        request.send(null);
    }
}

function processLoginResponse(response) {
    var parts = response.split(',');
    if (parts.length > 0 && parts[0] == 'Y') {
        setCookie('UID', parts[1], 365);
        setCookie('CID', parts[2], 365);
        setCookie('UN', parts[3], 365);
        closePanel();
        document.getElementById('UserWatchList').innerHTML = response;
        updateUserLoginState();
    }
    else {
        setErrorInPanel('LoginPanel_Status', parts[1]);
    }
}

function signupUser() {
    var email = validateField('SignupPanel_Email', fieldType.Email, 'SignupPanel_Status', 'Specify a valid email address.');
    var password2 = validateField('SignupPanel_Password2', fieldType.Password, 'SignupPanel_Status', 'Specify a password.');
    var password1 = validateField('SignupPanel_Password1', fieldType.Password, 'SignupPanel_Status', 'Specify a password.');
    var userName = validateField('SignupPanel_UserName', fieldType.AnyValue, 'SignupPanel_Status', 'Specify a user name.');

    if (email != null && password1 != null && password2 != null && userName != null) {
        if (password1 != password2) {
            setErrorInPanel('SignupPanel_Status', 'Specified passwords do not match.');
        }
        else {
            setWaitInPanel('SignupPanel_Status');
            request = createHttpRequest('/services/signup.aspx?u=' + encodeURIComponent(userName) + '&p=' + encodeURIComponent(password1) + '&e=' + encodeURIComponent(email));
            request.onreadystatechange = function () {
                if (request.readyState == 4) {
                    if (request.status == 200) {
                        processSignupResponse(request.responseText);
                    } else {
                        setErrorInPanel('SignupPanel_Status', g_msgErrorCommServer);
                    }
                }
            }

            request.send(null);
        }
    }
}

function processSignupResponse(response) {
    var parts = response.split(',');
    if (parts.length > 0 && parts[0] == 'Y') {
        setCookie('UID', parts[1], 365);
        setCookie('CID', parts[2], 365);
        setCookie('UN', parts[3], 365);
        loadPanel('/services/done.aspx?t=signup', 'PopupPanel');
        updateUserLoginState();
    }
    else {
        setErrorInPanel('SignupPanel_Status', parts[1]);
    }
}

function forgotUser() {
    var username = trim(document.getElementById('ForgotPanel_UserName').value);
    var email = trim(document.getElementById('ForgotPanel_Email').value);

    if (username == '' && email == '') {
        setErrorInPanel('ForgotPanel_Status', 'Enter a valid email address or a user name.');
    }
    else {
        setWaitInPanel('ForgotPanel_Status');
        request = createHttpRequest('/services/forgot.aspx?u=' + encodeURIComponent(username) + '&e=' + encodeURIComponent(email));
        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                if (request.status == 200) {
                    processForgotResponse(request.responseText);
                } else {
                    setErrorInPanel('ForgotPanel_Status', g_msgErrorCommServer);
                }
            }
        }

        request.send(null);
    }
}

function processForgotResponse(response) {
    var parts = response.split(',');
    if (parts.length > 0 && parts[0] == 'Y') {
        loadPanel('/services/done.aspx?t=ForgotPassword', 'PopupPanel');
    }
    else {
        setErrorInPanel('ForgotPanel_Status', parts[1]);
    }
}

function emailFriend() {
    var message = validateField('EmailPanel_Message', fieldType.AnyValue, 'EmailPanel_Status', 'Enter a message to be included with the email.');
    var email = validateField('EmailPanel_Email', fieldType.Email, 'EmailPanel_Status', 'Enter a valid email address.');
    var name = validateField('EmailPanel_Name', fieldType.AnyValue, 'EmailPanel_Status', 'Enter your name.');

    if (name != null && email != null && message != null) {
        setWaitInPanel('EmailPanel_Status');
        request = createHttpRequest('/services/email.aspx?did=' + g_derivedId + '&n=' + encodeURIComponent(name) + '&e=' + encodeURIComponent(email) + '&m=' + encodeURIComponent(message));
        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                if (request.status == 200) {
                    loadPanel('/services/done.aspx?t=EmailFriend', 'PopupPanel');
                } else {
                    setErrorInPanel('EmailPanel_Status', g_msgErrorCommServer);
                }
            }
        }

        request.send(null);
    }
}

function contactUs() {
    var issue = validateField('ContactPanel_Issue', fieldType.AnyValue, 'ContactPanel_Status', 'Please describe the issue.');
    var email = validateField('ContactPanel_Email', fieldType.AnyValue, 'ContactPanel_Status', 'Please your email address.');
    var name = validateField('ContactPanel_Name', fieldType.AnyValue, 'ContactPanel_Status', 'Please enter your name.');

    if (issue != null && email != null && name != null) {
        setWaitInPanel('ContactPanel_Status');
        request = createHttpRequest('/services/contactus.aspx?n=' + encodeURIComponent(name) + '&e=' + encodeURIComponent(email) + '&i=' + encodeURIComponent(issue));
        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                if (request.status == 200) {
                    loadPanel('/services/done.aspx?t=ContactUs', 'PopupPanel');
                } else {
                    setErrorInPanel('ContactPanel_Status', g_msgErrorCommServer);
                }
            }
        }

        request.send(null);
    }
}

function largeImagePanel(derivedId) {
    loadPanel('/services/largeimage.aspx?did=' + derivedId, 'PopupPanel');
}

function addAlert() {
    var price = validateField('AddAlertPanel_Price', fieldType.Price, 'AddAlertPanel_Status', 'Please specify a valid target price.');

    if (price != null) {
        setWaitInPanel('AddAlertPanel_Status');
        request = createHttpRequest('/services/alert.aspx?op=add&did=' + g_derivedId + '&p=' + price);
        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                if (request.status == 200) {
                    var list = request.responseText.split(',');
                    if (list[0] == 'Y') {
                        document.getElementById('UserWatchList').innerHTML = request.responseText;
                        updateUserLoginState();
                        loadPanel('/services/done.aspx?t=AlertAdded', 'PopupPanel');
                    }
                    else {
                        setErrorInPanel('AddAlertPanel_Status', list[1]);
                    }
                } else {
                    setErrorInPanel('AddAlertPanel_Status', g_msgErrorCommServer);
                }
            }
        }

        request.send(null);
    }
}

function updateAlert() {
    var price = validateField('UpdateAlertPanel_Price', fieldType.Price, 'UpdateAlertPanel_Status', 'Please specify a valid target price.');

    if (price != null) {
        setWaitInPanel('UpdateAlertPanel_Status');
        request = createHttpRequest('/services/alert.aspx?op=update&did=' + g_derivedId + '&p=' + price);
        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                if (request.status == 200) {
                    var list = request.responseText.split(',');
                    if (list[0] == 'Y') {
                        document.getElementById('UserWatchList').innerHTML = request.responseText;
                        updateUserLoginState();
                        if (g_backToMyAccount) {
                            alertsListPanel();
                        }
                        else {
                            loadPanel('/services/done.aspx?t=AlertUpdated', 'PopupPanel');
                        }
                    }
                    else {
                        setErrorInPanel('UpdateAlertPanel_Status', list[1]);
                    }
                } else {
                    setErrorInPanel('UpdateAlertPanel_Status', g_msgErrorCommServer);
                }
            }
        }

        request.send(null);
    }
}

function deleteAlert() {
    setWaitInPanel('UpdateAlertPanel_Status');
    request = createHttpRequest('/services/alert.aspx?op=remove&did=' + g_derivedId);
    request.onreadystatechange = function () {
        if (request.readyState == 4) {
            if (request.status == 200) {
                var list = request.responseText.split(',');
                if (list[0] == 'Y') {
                    document.getElementById('UserWatchList').innerHTML = request.responseText;
                    updateUserLoginState();
                    if (g_backToMyAccount) {
                        alertsListPanel();
                    }
                    else {
                        loadPanel('/services/done.aspx?t=AlertRemoved', 'PopupPanel');
                    }
                }
                else {
                    setErrorInPanel('UpdateAlertPanel_Status', list[1]);
                }
            } else {
                setErrorInPanel('UpdateAlertPanel_Status', g_msgErrorCommServer);
            }
        }
    }

    request.send(null);
}

function changePassword() {
    var newp2 = validateField('PasswordPanel_New2', fieldType.Password, 'PasswordPanel_Status', 'Re-enter your new password.');
    var newp = validateField('PasswordPanel_New', fieldType.Password, 'PasswordPanel_Status', 'Specify new current password.');
    var old = validateField('PasswordPanel_Old', fieldType.Password, 'PasswordPanel_Status', 'Specify your current password.');

    if (newp != newp2) {
        setErrorInPanel('PasswordPanel_Status', 'Your new password does not match the re-entered password.');
    }
    else if (old != null && newp != null && newp2 != null) {
        setWaitInPanel('PasswordPanel_Status');
        request = createHttpRequest('/services/changePassword.aspx?o=' + old + '&n=' + newp);
        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                if (request.status == 200) {
                    var list = request.responseText.split(',');
                    if (list[0] == 'Y') {
                        loadPanel('/services/done.aspx?t=ChangePassword', 'PopupPanel');
                    }
                    else {
                        setErrorInPanel('PasswordPanel_Status', list[1]);
                    }
                } else {
                    setErrorInPanel('PasswordPanel_Status', g_msgErrorCommServer);
                }
            }
        }

        request.send(null);
    }
}
///////////////////////////////////////////////////////////
// Panel Management
///////////////////////////////////////////////////////////

function showPanel(id) {
    var panel = document.getElementById(id);
    var posX, posY;

    closePanel();
    if (panel.offsetWidth > document.documentElement.clientWidth) {
        posX = 0;
    } else {
        posX = (document.documentElement.clientWidth - panel.offsetWidth) / 2;
    }

    if (panel.offsetHeight > document.documentElement.clientHeight) {
        posY = 0;
    } else {
        posY = (document.documentElement.clientHeight - panel.offsetHeight) / 2;
    }

    panel.style.left = posX + 'px';
    panel.style.top = posY + 'px';

    document.getElementById(id).style.visibility = 'visible';
}

function loginPanel() {
    loadPanel('/panels/login.html', 'PopupPanel');
}

function signupPanel() {
    loadPanel('/panels/signup.html', 'PopupPanel');
}

function forgotPanel() {
    loadPanel('/panels/forgot.html', 'PopupPanel');
}

function emailPanel(derivedId) {
    g_derivedId = derivedId;
    loadPanel('/panels/email.aspx', 'PopupPanel');
}

function graphPanel(derivedId) {
    loadPanel('/services/pricegraph.aspx?did=' + derivedId, 'GraphPopupPanel');
}

function pricePanel(derivedId) {
    loadPanel('/services/pricetable.aspx?did=' + derivedId, 'PriceTablePopupPanel');
}

function contactPanel() {
    loadPanel('/panels/contactpanel.html', 'PopupPanel');
}

function addAlertPanel(derivedId) {
    g_derivedId = derivedId;
    if (getUser() == null) {
        loadPanel('/panels/loginRequired.html', 'PopupPanel');
    }
    else {
        loadPanel('/panels/addAlert.aspx?did=' + encodeURIComponent(derivedId), 'BigPopupPanel');
    }
}

function updateAlertPanel(derivedId, backToMyAccount) {
    g_derivedId = derivedId;
    g_backToMyAccount = backToMyAccount;
    if (getUser() == null) {
        loadPanel('/panels/loginRequired.html', 'PopupPanel');
    }
    else {
        loadPanel('/panels/updateAlert.aspx?did=' + encodeURIComponent(derivedId), 'BigPopupPanel');
    }
}

function myAccountPanel() {
    if (getUser() == null) {
        loadPanel('/panels/loginRequired.html', 'PopupPanel');
    }
    else {
        loadPanel('/panels/myaccount.html', 'PopupPanel');
    }
}

function changePasswordPanel() {
    if (getUser() == null) {
        loadPanel('/panels/loginRequired.html', 'PopupPanel');
    }
    else {
        loadPanel('/panels/changePassword.html', 'PopupPanel');
    }
}

function alertsListPanel() {
    if (getUser() == null) {
        loadPanel('/panels/loginRequired.html', 'PopupPanel');
    }
    else {
        loadPanel('/panels/alertList.aspx', 'BigPopupPanel');
    }
}

function loadPanel(url, targetPanel) {
    showPanel('WaitPanel');
    request = createHttpRequest(url);
    request.onreadystatechange = function () {
        if (request.readyState == 4) {
            if (request.status == 200) {
                var panel = document.getElementById(targetPanel);
                panel.innerHTML = request.responseText;
                showPanel(targetPanel);
            } else {
                showPanel('ErrorPanel');
            }
        }
    }

    request.send(null);   
}

function closePanel() {
    document.getElementById('ErrorPanel').style.visibility = 'hidden';
    document.getElementById('WaitPanel').style.visibility = 'hidden';
    document.getElementById('PopupPanel').style.visibility = 'hidden';
    document.getElementById('BigPopupPanel').style.visibility = 'hidden';
    document.getElementById('GraphPopupPanel').style.visibility = 'hidden';
    document.getElementById('PriceTablePopupPanel').style.visibility = 'hidden';
}

function setWaitInPanel(id) {
    var elem = document.getElementById(id);

    elem.innerHTML = '<img src="/images/please_wait.gif" style="vertical-align: middle;" /> Please Wait...';
    elem.style.color = '#000';
    elem.style.display = 'inline';
}

function setErrorInPanel(id, msg) {
    var elem = document.getElementById(id);
    elem.innerHTML = '* ' + msg;
    elem.style.color = '#f00';
    elem.style.display = 'inline';
}