﻿function gelv(s) {
    return document.getElementById(s).value;
}
function isValidDate(val) {
    var regexp = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
    var ret = false;
    if (val.match(regexp) && val != "") ret = true;
    return ret;
}
sfHover = function() {
    var sfEls = document.getElementById("nav").getElementsByTagName("LI");
    for (var i = 0; i < sfEls.length; i++) {
        sfEls[i].onmouseover = function() {
            this.className += " sfhover";
        }
        sfEls[i].onmouseout = function() {
            this.className = this.className.replace(new RegExp(" sfhover\\b"), "");
        }
    }
}
YAHOO.namespace('AL.util');
function trim(val) {
    var s = String(val);
    return s.replace(/^\s*|\s*$/g, "");
}
function validInt(fld, nm, zero) {
    var v = trim(document.getElementById(fld).value);
    var bRet = true;
    if (v != "") {
        if (isNaN(v) == true) bRet = false;
        if (isNaN(v) == false && v < 0) bRet = false;
        if (isNaN(v) == false && zero == false && v == 0) bRet = false;
        if (isNaN(v) == false && (v % 1) != 0) bRet = false;
    }
    if (!bRet) return "Your " + nm + " must be a positive integer. "; else return "";
}
function validDec(fld, nm, zero) {
    var v = trim(document.getElementById(fld).value);
    var bRet = true;
    if (v != "") {
        if (isNaN(v) == true) bRet = false;
        if (isNaN(v) == false && v < 0) bRet = false;
        if (isNaN(v) == false && zero == false && v == 0) bRet = false;
    }
    if (!bRet) return "Your " + nm + " must be a positive numeric value. "; else return "";
}

YAHOO.AL.util.JSON = new function() {
    var useHasOwn = {}.hasOwnProperty ? true : false;
    var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;

    var pad = function(n) {
        return n < 10 ? '0' + n : n;
    };

    var m = {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"': '\\"',
        '\\': '\\\\'
    };

    var encodeString = function(s) {
        if (/["\\\x00-\x1f]/.test(s)) {
            return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                var c = m[b];
                if (c) {
                    return c;
                }
                c = b.charCodeAt();
                return '\\u00' +
                    Math.floor(c / 16).toString(16) +
                    (c % 16).toString(16);
            }) + '"';
        }
        return '"' + s + '"';
    };

    var encodeArray = function(o) {
        var a = ['['], b, i, l = o.length, v;
        for (i = 0; i < l; i += 1) {
            v = o[i];
            switch (typeof v) {
                case 'undefined':
                case 'function':
                case 'unknown':
                    break;
                default:
                    if (b) {
                        a.push(',');
                    }
                    a.push(v === null ? "null" : YAHOO.AL.util.JSON.encode(v));
                    b = true;
            }
        }
        a.push(']');
        return a.join('');
    };

    var encodeDate = function(o) {
        return '"' + o.getFullYear() + '-' +
                pad(o.getMonth() + 1) + '-' +
                pad(o.getDate()) + 'T' +
                pad(o.getHours()) + ':' +
                pad(o.getMinutes()) + ':' +
                pad(o.getSeconds()) + '"';
    };

    this.encode = function(o) {
        if (typeof o == 'undefined' || o === null) {
            return 'null';
        } else if (o instanceof Array) {
            return encodeArray(o);
        } else if (o instanceof Date) {
            return encodeDate(o);
        } else if (typeof o == 'string') {
            return encodeString(o);
        } else if (typeof o == 'number') {
            return isFinite(o) ? String(o) : "null";
        } else if (typeof o == 'boolean') {
            return String(o);
        } else {
            var a = ['{'], b, i, v;
            for (var i in o) {
                if (!useHasOwn || o.hasOwnProperty(i)) {
                    v = o[i];
                    switch (typeof v) {
                        case 'undefined':
                        case 'function':
                        case 'unknown':
                            break;
                        default:
                            if (b) {
                                a.push(',');
                            }
                            a.push(this.encode(i), ':',
                                v === null ? "null" : this.encode(v));
                            b = true;
                    }
                }
            }
            a.push('}');
            return a.join('');
        }
    };

    this.decode = function(json) {
        try {
            if (validRE.test(json)) {
                return eval('(' + json + ')');
            }
        } catch (e) {
        }
        throw new SyntaxError("parseJSON");
    };
} ();

//rpc
var rpc = {
    "successevent": "",
    "failuremsg": "",
    "ShowProgressDialog": false,

    handleSuccess: function(o) {
        if (ShowProgressDialog) YAHOO.example.container.wait.hide();
        if (o.responseText == "<ERROR />") {
            if (failuremsg != "") {
                alert(failuremsg);
            }
        }
        else {
            successevent(o.responseText);
        }
    },
    handleFailure: function(o) {
        if (ShowProgressDialog) YAHOO.example.container.wait.hide();
        if (failuremsg != "") alert(failuremsg);
    },
    startRequest: function(sucevnt, failmsg, url, params) {
        successevent = sucevnt;
        failuremsg = failmsg;
        ShowProgressDialog = true;
        showProgress();
        YAHOO.util.Connect.asyncRequest('POST', url, callback, params);
    },
    startRequestNoProgress: function(sucevnt, failmsg, url, params) {
        successevent = sucevnt;
        failuremsg = failmsg;
        ShowProgressDialog = false;
        //showProgress();
        YAHOO.util.Connect.asyncRequest('POST', url, callback, params);
    }
};
var callback =
{
    success: rpc.handleSuccess,
    failure: rpc.handleFailure,
    scope: rpc
};

YAHOO.namespace("example.container");
function showProgress() {
    if (!YAHOO.example.container.wait) {
        // Initialize the temporary Panel to display while waiting for external content to load
        YAHOO.example.container.wait =
                new YAHOO.widget.Panel("wait",
                                                { width: "240px",
                                                    fixedcenter: true,
                                                    close: false,
                                                    draggable: false,
                                                    modal: true,
                                                    visible: false
                                                }
                                            );
        YAHOO.example.container.wait.setHeader("Loading, please wait...");
        YAHOO.example.container.wait.setBody("<img src=\"http://staticimages.fitness-partners.com/static/images/loading.gif\"/>");
        YAHOO.example.container.wait.render(document.body);
    }
    YAHOO.example.container.wait.show();
}

function addFriend(uid) {
    rpc.startRequest(postAddFriend, "There was an unexpected problem trying to add this person as a friend.  Please try again.  This problem has been logged for evaluation by our support team.", "/rpc/suggestfriendship.ashx", "uid=" + uid)
}
function postAddFriend(response) {
    alert(response);
}

/* Support for uploading pictures)*/
var dlgAddPicture;
var _InternalKey = 0;
function addPicture(id) {
    _InternalKey = id;
    if (!dlgAddPicture) { // lazy initialize the dialog and only create it once
        document.getElementById("divAddPicture").style.display = "";
        dlgAddPicture = new YAHOO.widget.Dialog("divAddPicture",
											    { width: 600,
											        fixedcenter: true,
											        draggable: true,
											        visible: false,
											        modal: true,
											        constraintoviewport: true,
											        zindex: 9001,
											        postmethod: '',
											        buttons: [{ text: "Add Picture", handler: uploadPicture, isDefault: true}]
											    });
        dlgAddPicture.render(document.body);
    }
    dlgAddPicture.show();
}

var uploadHandler = {
    upload: function(o) {
        YAHOO.example.container.wait.hide();
        alert("finished");
    }
};

function uploadPicture() {
    YAHOO.util.Connect.setForm('testForm', true);
    YAHOO.util.Connect.asyncRequest('POST', '/rpc/pictureupload.ashx', uploadHandler, "key=" + _InternalKey);
    dlgAddPicture.hide();
    showProgress();
}
var dlgAddPicture;
var _InternalKey = 0;
function addPicture(id) {
    _InternalKey = id;
    if (!dlgAddPicture) { // lazy initialize the dialog and only create it once
        document.getElementById("divAddPicture").style.display = "";
        dlgAddPicture = new YAHOO.widget.Dialog("divAddPicture",
											    { width: 600,
											        fixedcenter: true,
											        draggable: true,
											        visible: false,
											        modal: true,
											        constraintoviewport: true,
											        zindex: 9001,
											        postmethod: '',
											        buttons: [{ text: "Add Picture", handler: uploadPicture, isDefault: true}]
											    });
        dlgAddPicture.render(document.body);
    }
    dlgAddPicture.show();
}

var uploadHandler = {
    upload: function(o) {
        YAHOO.example.container.wait.hide();
        alert("finished");
    }
};

function uploadPicture() {
    YAHOO.util.Connect.setForm('testForm', true);
    YAHOO.util.Connect.asyncRequest('POST', '/rpc/pictureupload.ashx', uploadHandler, "key=" + _InternalKey);
    dlgAddPicture.hide();
    showProgress();
}
var dlgAddPicture;
var _InternalKey = 0;
function addPicture(id) {
    _InternalKey = id;
    if (!dlgAddPicture) { // lazy initialize the dialog and only create it once
        document.getElementById("divAddPicture").style.display = "";
        dlgAddPicture = new YAHOO.widget.Dialog("divAddPicture",
											    { width: 600,
											        fixedcenter: true,
											        draggable: true,
											        visible: false,
											        modal: true,
											        constraintoviewport: true,
											        zindex: 9001,
											        postmethod: '',
											        buttons: [{ text: "Add Picture", handler: uploadPicture, isDefault: true}]
											    });
        dlgAddPicture.render(document.body);
    }
    dlgAddPicture.show();
}

var uploadHandler = {
    upload: function(o) {
        YAHOO.example.container.wait.hide();
        alert("finished");
    }
};

function uploadPicture() {
    YAHOO.util.Connect.setForm('formPictureUpload', true);
    YAHOO.util.Connect.asyncRequest('POST', '/rpc/pictureupload.ashx', uploadHandler, "key=" + _InternalKey);
    dlgAddPicture.hide();
    showProgress();
}
/*End of Uploading Pictures*/

/*Common Popups*/
var PostEventMethod;
var popupAlert = function() {
    var dialog;
    return {
        init: function() {
        },
        hide: function() {
            dialog.hide();
        },
        getPostEventMethod: function() {
            PostEventMethod;
        },
        showPopup: function(msg, evt) {
            if (!dialog) {
                document.getElementById("divAlertPopup").style.display = "";
                dialog = new YAHOO.widget.Dialog("divAlertPopup", { width: "485px", fixedcenter: true, draggable: true, visible: false, modal: true, constraintoviewport: true, zindex: 9001, postmethod: '', buttons: [{ text: "OK", handler: clickAlertPopup, isDefault: true}] });
                dialog.cfg.queueProperty("postmethod", "form");
                dialog.render(document.body);
            }
            document.getElementById("AlertMessage").innerHTML = msg;
            PostEventMethod = evt;
            dialog.show();
        }
    };
} ();
function clickAlertPopup() {
    popupAlert.hide();
    if (PostEventMethod != null) {
        PostEventMethod();
    }
}
/*End of Common Popups*/


//rpc2
var rpc2 = {
    "successevent": "",
    "failuremsg": "",
    "ShowProgressDialog": false,

    handleSuccess: function(o) {
        if (ShowProgressDialog) YAHOO.example.container.wait.hide();
        var ReturnData = YAHOO.lang.JSON.parse(o.responseText);
        if (!ReturnData.Successful) {
            if (ReturnData.ReturnMessage != "") {
                alert(ReturnData.ReturnMessage);
            }
            else {
                if (failuremsg != "") {
                    alert(failuremsg);
                }
            }
        }
        else {
            successevent(ReturnData);
        }
    },
    handleFailure: function(o) {
        if (ShowProgressDialog) YAHOO.example.container.wait.hide();
        if (failuremsg != "") alert(failuremsg);
    },
    startRequest: function(sucevnt, failmsg, url, params) {
        successevent = sucevnt;
        failuremsg = failmsg;
        ShowProgressDialog = true;
        showProgress();
        YAHOO.util.Connect.asyncRequest('POST', url, callback2, params);
    },
    startRequestNoProgress: function(sucevnt, failmsg, url, params) {
        successevent = sucevnt;
        failuremsg = failmsg;
        ShowProgressDialog = false;
        //showProgress();
        YAHOO.util.Connect.asyncRequest('POST', url, callback2, params);
    }
};
var callback2 =
{
    success: rpc2.handleSuccess,
    failure: rpc2.handleFailure,
    scope: rpc2
};
var SuccessCallbackFunc;

function genericSaveChanges(Fields, saveurl, SuccessCallback, InterceptFunction) {
    var data = {};
    for (var x = 0; x < Fields.TextFields.length; x++) {
        data[Fields.TextFields[x]] = document.getElementById(Fields.TextFields[x]).value;
    }
    for (var x = 0; x < Fields.DropDownFields.length; x++) {
        data[Fields.DropDownFields[x]] = document.getElementById(Fields.DropDownFields[x]).options[document.getElementById(Fields.DropDownFields[x]).selectedIndex].value;
    }
    for (var x = 0; x < Fields.CheckFields.length; x++) {
        if (document.getElementById(Fields.CheckFields[x]).checked) {
            data[Fields.CheckFields[x]] = true;
        }
        else {
            data[Fields.CheckFields[x]] = false;
        }
    }
    if (Fields.TextCollFields != null) {
        for (var x = 0; x < Fields.TextCollFields.length; x++) {
            var fld = Fields.TextCollFields[x];
            for (var y = 0; y < fld.Fields.length; y++) {
                var s = trim(document.getElementById(fld.Fields[y]).value);
                if (s != "") {
                    if (data[fld.FieldName] == null) data[fld.FieldName] = [];
                    data[fld.FieldName].push(s);
                }
            }
        }
    }
    if (InterceptFunction != null) {
        InterceptFunction(data);
    }
    SuccessCallbackFunc = SuccessCallback;
    rpc2.startRequest(genericSaveChangesComplete, "There was a problem saving this information.  Please try again.  If the problem persists please let support know via the 'Feedback' link at the bottom of the page.", saveurl, "data=" + escape(YAHOO.lang.JSON.stringify(data)));
}
function genericSaveChangesComplete(ReturnData) {
    alert(ReturnData.ReturnMessage);
    if (SuccessCallbackFunc != null) {
        SuccessCallbackFunc(ReturnData);
    }
}

