﻿GOFISH = YAHOO.namespace('GOFISH');

//  DOM is loaded before Window is loaded

// GOFISH data
GOFISH.arySalaryRange = ["&lt; 40K", "40K - 50K", "50K - 60K", "60K - 70K", "70K - 80K", "80K - 90K", "90K - 100K", "100K - 120K", "120K - 140K", "140K - 170K", "170K - 200K", "200K+"];
GOFISH.aryHourlyRange = ["20 - 30", "30 - 40", "40 - 50", "50 - 60", "60 - 70", "70 - 80", "80 - 90", "90 - 100", "100 - 125", "125 - 150", "150 - 175", "175 - 200", "200+"];
GOFISH.aryYearsExperience = ["1 - 2 years", "2 - 4 years", "4 - 7 years", "7 - 10 years", "10 - 15 years", "15 - 20 years", "20+"];
GOFISH.aryDegrees = ["High School", "Vocational", "Associates", "Bachelors", "Masters", "Doctorate"];
GOFISH.aryFeeSplit = ["10/90", "20/80", "30/70", "40/60", "50/50", "60/40", "70/30", "80/20", "90/10"];
GOFISH.networkList = [0];
GOFISH.networkListLoaded = false;
GOFISH.filterStateList = '';

// return the responseSchema for a dataSource based on the action that is passed in
GOFISH.getSchemaFromAction = function(action) {
    var ary = [];

    switch (action) {
        case 'findFish':
            ary = [{ key: 'ID', parser: YAHOO.util.DataSource.parseNumber }, 'Name', 'Email', 'CoreSkills', 'Title', "LocationID", "LocationText", 'ResidentLocation', 'Salary', 'Terms', 'Engagement', 'Exclusive', 'ShowContact', 'Active', 'Phone'];
            break;
        case 'findPond':
            ary = [{ key: 'ID', parser: YAHOO.util.DataSource.parseNumber }, 'CoreSkills', 'Title', 'LocationText', 'Salary', 'Terms', 'ShowContact', 'Active', 'OwnerID'];
            break;
        case 'myContacts':
            ary = [{ key: 'ID', parser: YAHOO.util.DataSource.parseNumber }, 'Email', 'ContactName', 'Company', 'PhoneNumber', 'Email', 'CompanyWebSite', 'CoreSkills', 'Candidates', 'Jobs', 'EngagedCandidates', 'EngagedJobs'];
            break;
        case 'myFish':
            ary = [{ key: 'ID', parser: YAHOO.util.DataSource.parseNumber }, 'Name', 'Email', 'CoreSkills', 'Title', "LocationID", 'ResidentLocation', 'Salary', 'Terms', 'Engagement', 'Exclusive', 'ShowContact', 'Active', 'Phone'];
            break;
        case 'myPond':
            ary = [{ key: 'ID', parser: YAHOO.util.DataSource.parseNumber }, 'CoreSkills', 'Title', "LocationID", 'Salary', 'Terms', 'ShowContact', 'CompanyName', 'ContactName', 'Phone', 'Email', 'Active', 'LocationText'];
            break;
    }

    return ary;
}

GOFISH.dataSource_JSON = new YAHOO.util.DataSource('data_JSON.aspx');
GOFISH.dataSource_JSON.responseType = YAHOO.util.DataSource.TYPE_JSON;
GOFISH.dataSource_JSON.connXhrMode = "queueRequests";


gfSearchObject = function () {
    if (gfSearchObject.arguments.length > 0) { var obj = gfSearchObject.arguments[0]; }

    var errMsg = '';

    // action, dataSource, dataTable, filter
    if (obj.action == null) { errMsg += 'Missing action parameter\n'; }
    if (obj.source == null) { obj.source = 'data_JSON.aspx?'; }
    if (obj.resultsTo == null) { obj.resultsTo = 'searchResults'; }
    if (obj.cols == null) { errMsg += 'Missing column definitions\n'; }
    if (obj.filterField == null) { obj.filterField = 'txtSearchFilter'; }

    this.paramBase = "&params=" + Dom.get("CompanyID").value + '|' + GOFISH.userSecToken;
    this.paramString = '';
    this.skillSearch = '';
    this.locationSearch = '';
    this.locationList = '';
    this.industryList = '';

    this.paramString_Build = function() {
        var filter = this.paramBase;
        var el;

        try {
            // update search options prior to building new string
            if (Dom.get('SkillSearch')) { this.skillSearch = Dom.get('SkillSearch').value; }
            if (Dom.get('LocationSearch')) { this.locationSearch = Dom.get('LocationSearch').value; }

            if (typeof (txtSearchFilter) == 'object') { if (txtSearchFilter.length > 0) { filter += '|' + txtSearchFilter.getValue(); } }
            if (this.skillSearch.length > 0) { filter += '|' + this.skillSearch; }
            if (this.locationSearch.length > 0) { filter += '|' + this.locationSearch; }

            // The following items are passed as their own name/value pair
            if (DOM.get('selNetworkFilter')) {
                el = DOM.get('selNetworkFilter')
                if (el.options.length > 0) {
                    filter += '&networkList=' + el.options[el.selectedIndex].value;
                }
            }
        }
        catch (e) { alert(e); }

        this.paramString = filter;
        //alert('paramString: ' + this.paramString);
    }

    if (errMsg.length == 0) {
        try {
            this.action = obj.action;
            this.cols = obj.cols;
            this.resultsTo = obj.resultsTo;
            this.filter = obj.filter;
            this.filterField = obj.filterField;
            this.hasFilter = typeof (document.getElementById(this.filterField)) == 'object';
            this.filterTimeout = null;
            this.report = function() { return this.action; };

            this.dataSource = new YAHOO.util.DataSource("data_JSON.aspx?action=" + this.action);
            this.dataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
            this.dataSource.connXhrMode = "queueRequests";
            this.dataSource.responseSchema = {
                resultsList: "records",
                fields: GOFISH.getSchemaFromAction(this.action)
            };
        }
        catch (e) { alert(e); }

        //alert('building');

        this.paramString_Build();
        //alert(this.paramString);

        this.dataTable = new YAHOO.widget.DataTable(
                      this.resultsTo
                    , this.cols
                    , this.dataSource
                    , { initialRequest: this.paramString,
                        paginator: new YAHOO.widget.Paginator({
                            rowsPerPage: 15,
                            containers: ['pagingBelow']
                        })
                    }
                );
    }
    else {
        alert(errMsg);
    }

    this.updateFilter = function() {
        // Reset timeout
        this.filterTimeout = null;
        this.paramString_Build();

        //alert("&params=" + Dom.get("CompanyID").value + "|" + txtSearchFilter.getValue());

        // Reset sort
        //                var state = this.dataTable.getState();
        //                state.sortedBy = { key: 'Name', dir: YAHOO.widget.DataTable.CLASS_ASC };

        //                // Get filtered data
        var filter = '';
        //alert('Setting Filter\n:' + typeof (txtSearchFilter));
        try {
            if (typeof (txtSearchFilter) == 'object') { if (txtSearchFilter.length > 0) { filter += '|' + txtSearchFilter.getValue(); } }

            filter += GOFISH.filterStateList;

            //alert(this.paramString);
            gfSearch.dataTable.requery(this.paramString);
        }
        catch (e) { alert(e); }
        //alert('working');
    };
};
// End object definition

GOFISH.pnlCandidateDetails = '';

GOFISH.pnlCandidateDetail_Fill = function(oResponse) {
    try {
        var obj = GOFISH.pnlCandidateDetails;
        var data = YAHOO.lang.JSON.parse(oResponse.responseText);
        data = data.records[0];

        DOM.get('canInf_Name').innerHTML = data.Name;
        DOM.get('canInf_Email').innerHTML = data.Email;
        DOM.get('canInf_Phone').innerHTML = data.Phone;
        DOM.get('canInf_Address1').innerHTML = data.Address1;
        DOM.get('canInf_Address2').innerHTML = data.Address2;
        DOM.get('canInf_CityStateZip').innerHTML = data.City + ', ' + data.State + ' ' + data.PostalCode;
    }
    catch (e) { alert(e); }
}

GOFISH.networkList_Fill = function(oResponse) {
    // adjust networkList to reflect user's available networks
    //alert('networkList_Fill\n\n' + oResponse.responseText);
    var oData = YAHOO.lang.JSON.parse(oResponse.responseText);

    try {
        GOFISH.networkList = oData.responseObject.NetworkList;

        if (DOM.get('divNetworkFilter') && GOFISH.networkList.length > 3) {
            // Add options to NetworkFilter
            var el = DOM.get('selNetworkFilter');
            gofish_SelectList_Append({ element: el, value: '0,1', text: 'Entire Network' });
            gofish_SelectList_Append({ element: el, value: '1', text: 'MRI Network Only' });
            //gofish_SelectList_Append({ element: el, value: '0', text: 'GoFish Network' });

            Dom.setStyle('divNetworkFilter', 'visibility', 'visible');
        }

    }
    catch (e) { alert(e); }
}


var ajaxNetworkList = {
    params: '',

    handleSuccess: function(oResponse) {
        //alert(oResponse.responseText + '\n\n' + oResponse.argument[0]);
        GOFISH.networkList_Fill(oResponse);
    },

    handleFailure: function(o) {
        // Failure handler
        //alert('Fail\n\n' + o.getAllResponseHeaders);
    },

    startRequest: function() {
        YAHOO.util.Connect.asyncRequest('POST', 'data_JSON.aspx?action=RecNetID&params='+ document.getElementById('CompanyID').value + '|' + GOFISH.userSecToken,
            {
                success: this.handleSuccess,
                failure: this.handleFailure,
                scope: this,
                argument: [this.params]
            },
             this.params
        );
    }
};

function gofish_SelectList_Append(obj) {
    // obj.element
    // obj.value
    // obj.text
    // obj.targetType 'text' or 'value'
    // obj.target

    if (obj.targetType == null) { obj.targetType = 'text' }

    try {
        var tmpOption = document.createElement('option');
        tmpOption.setAttribute('value', obj.value);

        if (obj.target != null) {
            if (obj.targetType == 'text' && obj.target == obj.text) {
                tmpOption.setAttribute('selected', true);
            }
            else if (obj.targetType == 'value' && obj.target == obj.value) {
                tmpOption.setAttribute('selected', true);
            }
        }

        tmpOption.innerHTML = obj.text;
        obj.element.appendChild(tmpOption);
    }
    catch (e) { alert(e); }
}

// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
    if (!radioObj)
        return "";
    var radioLength = radioObj.length;
    if (radioLength == undefined)
        if (radioObj.checked)
        return radioObj.value;
    else
        return "";
    for (var i = 0; i < radioLength; i++) {
        if (radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return "";
}

// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
    if (!radioObj)
        return;
    var radioLength = radioObj.length;
    if (radioLength == undefined) {
        radioObj.checked = (radioObj.value == newValue.toString());
        return;
    }
    for (var i = 0; i < radioLength; i++) {
        radioObj[i].checked = false;
        if (radioObj[i].value == newValue.toString()) {
            radioObj[i].checked = true;
        }
    }
}

// BEGIN Header Stats
YAHOO.util.Event.addListener(window, "load", function() {
    // isRECRUITER is set in header
if (document.getElementById('pageHeader_pnlLoggedIn') != null && isRECRUITER && isLOGGEDIN) {
        //        var hdrRight_datasource = new YAHOO.util.XHRDataSource("data_JSON.aspx?action=hdrRight_Stats");
        var oRequest = "params=" + USERID + "|";

        var hdrRight_loadStats = function(obj) {
            try {
                var data = YAHOO.lang.JSON.parse(obj.responseText);
                //alert(obj.responseText);
                var stats = data.responseObject;
                //alert(stats);

                // Take passed in object literal and fill in stats
                //  Object should have same properties as hdrRight_currentStats
                //  values will be compared to determine state of displayed text
                // check for existence of user panel and then add stat fields as needed
                hdrRight_Obj = document.getElementById('pageHeader_pnlLoggedIn');
                hdrRight_ObjMessages = document.getElementById('hdrRight_Messages');
                hdrRight_ObjCandidates = document.getElementById('hdrRight_Candidates');
                hdrRight_ObjJobs = document.getElementById('hdrRight_Jobs');

                if (hdrRight_Obj != null) {
                    hdrRight_currentStats.canCount = stats.CandidateCount;
                    hdrRight_currentStats.jobCount = stats.JobCount;

                    if (obj.msgCount != hdrRight_currentStats.msgCount) {
                        // Update innerHTML
                        hdrRight_ObjMessages.innerHTML = '<strong><a href="Messages.aspx">New Messages</a>: ' + stats.Messages + '</strong>';
                        hdrRight_currentStats.msgCount = obj.msgCount;
                    }

                    hdrRight_ObjCandidates.innerHTML = 'Candidates: ' + stats.CandidateCount + '';
                    hdrRight_ObjJobs.innerHTML = 'Jobs: ' + stats.JobCount + '';

                    // Check for postings and display MinPostAlert if need be
                    //if (hdrRight_currentStats.canCount == 0 && hdrRight_currentStats.jobCount == 0) {
                    if (1==2 && hdrRight_currentStats.canCount == 0 && hdrRight_currentStats.jobCount == 0 && isMinPostAlerted == 0) {
                        //alert('Post some dudes');

                        mySimpleDialog = new YAHOO.widget.SimpleDialog("dlgMinPost", {
                            width: "400px",
                            height: "270px",
                            effect: { effect: YAHOO.widget.ContainerEffect.FADE,
                                duration: 0.15
                            },
                            fixedcenter: true,
                            modal: true,
                            visible: false,
                            draggable: false
                        });
                        mySimpleDialog.setHeader("&nbsp;");
                        mySimpleDialog.setBody("<div style='font-size: 1.1em;'><center><div style='font-size: 1.1em;font-weight:bold;'>Post your Candidates and Jobs Now</div><h2>Make $10,000- $50,000 in 2010</h2></center><br /><p>To use Go Fish effectively, it is important that you post your candidates and/or jobs now and let Go Fish do the work for you.</p><p>It's easy, fast, and confidential.</p><p>Spend a few minutes posting now and make 2 - 5 extra placements in 2010.</p></div>");
                        mySimpleDialog.cfg.queueProperty("buttons", [{text:'OK', handler: function(){ mySimpleDialog.hide(); } }]);

                        mySimpleDialog.render(document.body);
                        mySimpleDialog.cfg.setProperty("fixedcenter", false);
                        mySimpleDialog.show();
                        setCountAlert();
                    }
                }
                else { return false; }
            }
            catch (e) { alert(e); }

        }

        var callback = { success: hdrRight_loadStats, failure: function() { alert('Server access failed'); } };

        try {
            //        hdrRight_datasource.responseType = YAHOO.util.XHRDataSource.TYPE_JSON;
            //        hdrRight_datasource.responseSchema = {
            //            resultList: "Response.responseText"
            //        };

            //        hdrRight_datasource.connXhrMode = "queueRequests";
            //        hdrRight_datasource.sendRequest("params=" + USERID + "|", callback);
            var sURL = "data_JSON.aspx?action=hdrRight_Stats&params=" + USERID + "&rnd" + Math.floor(Math.random() * 1000);
            //alert(sURL);
            var tran = YAHOO.util.Connect.asyncRequest('GET', sURL, callback, null);

            //hdrRight_currentStats.intervalID = hdrRight_datasource.setInterval(300000, oRequest, hdrRight_loadStats);
        }
        catch (e) { alert(e); }
    }

    function setCountAlert() {
        var sURL = "data_JSON.aspx?action=hdrRight_StatsAck&params=" + USERID + "&rnd" + Math.floor(Math.random() * 1000);
        //alert(sURL);
        var tran = YAHOO.util.Connect.asyncRequest('GET', sURL, { success: function() { return false; }, failure: function() { return false; } }, null);
    }

});

var hdrRight_currentStats = {
      canCount: 0
    , jobCount: 0
    , canCountEngaged: 0
    , jobCountEngaged: 0
    , msgCount: 0
    , intervalID: 0
    , isLoaded: false
};

// END Header Stats

