/***********************************
* actions.js
*
* Defines all the actions involving the use
* of the XMLHttpRequest object and remote
* asynchronous requests. Depends on YUI.
*
* Created By eculver
* Created On 08/21/08
************************************/

//var WEBROOT = '/coolproducts';        // eculver local webroot
//var WEBROOT = '/cp-v2-ec';        // proto dev webroot
var WEBROOT = '';            // production webroot

/***********************************
* contact-form submit event
*
* submits contact-form data to backend processor.
************************************/
function submitContactForm(id) {
    var frm = $('#' + id)[0];
    
    var handleSuccess = function(o){ 
        // hide notification message
        $('#contact-message').html("");
        
        if(o.responseText !== undefined && o.responseText.indexOf("true") >= 0){ 
            // everything went ok
            showAlert("Thank you for the message, we are very interested in hearing what you have to say!");
            frm.reset();
            $('#contact-message').html("<b>Thanks!</b>");
            $('#contact-success').fadeIn("def");
        } 
        
        else if(o.responseText !== undefined && (o.responseText.indexOf("empty field") >= 0)) {
            showAlert("Sorry, not all form fields were submitted.<br />Please try again.");
            frm.subject.focus();
        }
        
        else {
            showAlert("Sorry, we could not process your comments at this time.<br />Please try again or contact support directly. <support@coolproducts.com>");
            $('#contact-message').html("Sorry!");
        }
        
        // show loading indicator
        $('#global-loading').css("visibility", "hidden");
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    // make sure form is filled out correctly
    if(validateContactForm(frm)) {
        // show loading indicator
        $('#global-loading').css("visibility", "visible");
        
        // get contact-form data to be submitted
        YAHOO.util.Connect.setForm(frm);
        
        // set page to "loading"
        $('#contact-message').html("<b>Sending...<b>");
        
        // process contact-form
        var request = YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/processContactForm.php', callback);
    }
}

/***********************************
* login-form submit event
*
* submits login-form data to backend processor.
************************************/
function submitLoginForm(id, referer) {
    var frm = $('#' + id)[0];

    var handleSuccess = function(o){         
        // login succeeded
        if(o.responseText !== undefined && o.responseText.indexOf("true") >= 0){ 
            if(referer)
                window.location = referer;
            else
                window.location.reload();
        } 
        
        // login failed
        else
            showAlert('Login failed, please try again!', 'window.location="'+WEBROOT+'/login";');
            
        // show loading indicator
        $('#global-loading').css("visibility", "hidden");
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    // make sure form is filled out correctly
    if(validateLoginForm(frm)) {
        // show loading indicator
        $('#global-loading').css("visibility", "visible");
        
        // get login-form data to be submitted
        YAHOO.util.Connect.setForm(frm);
        
        // process login-form

        var request = YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/processLoginForm.php', callback);
    }
}

/***********************************
* doLogout event
*
* Does asynchronous request to log a user out
************************************/
function doLogout() {
    var handleSuccess = function(o){ 
        if(o.responseText !== undefined && o.responseText.indexOf("true") >= 0)
            window.location = WEBROOT + "/";
        else
            showAlert("Sorry, we could not process your logout at this time.<br />Please try again or contact support. <support@coolproducts.com>");
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    var request = YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/processLogoutForm.php', callback);
}

/***********************************
* reset-login-form submit event
*
* submits reset-login-form data to backend processor.
************************************/
function submitResetLoginForm(id) {
    var frm = $('#' + id)[0];

    var handleSuccess = function(o){ 
        
        if(o.responseText !== undefined && o.responseText.indexOf("true") >= 0){ 
            $('#reset-login-message').html("Please check your email for your new password");
            showAlert("A password notification has been sent!");
        } 
        else if(o.responseText !== undefined && o.responseText.indexOf("false - error: user not found") >=0) {
            $('#reset-login-message').html("<div style='color:red'>Email Not Found. Please Try Again</div>");
            showAlert("Sorry, we could not find anyone with that email address.<br />Please try again.");
        }
        else {
            $('#reset-login-message').html("<div style='color:red'>Sorry, There Was An Error.</div>");
            showAlert("Sorry, we could not process your password request at this time.<br />Please try again or contact support. <support@coolproducts.com>");
        }
        
        // hide loading indicator
        $('#global-loading').css("visibility", "hidden");
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    // make sure form is filled out correctly
    if(validateResetLoginForm(frm)) {
        // show loading indicator
        $('#global-loading').css("visibility", "visible");
        
        // get login-form data to be submitted
        YAHOO.util.Connect.setForm(frm);
        
        // set notification message
        $('#reset-login-message').html("Attempting Password Reset...");
        
        // process login-form
        var request = YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/processResetLoginForm.php', callback);
    }
}

/***********************************
* signup-form submit event
*
* submits signup-form data to backend processor.
************************************/
function submitSignupForm(id, referer) {
    var frm = $('#' + id)[0];
    
    var handleSuccess = function(o){ 
        // hide notification message
        $('#signup-message').html("");
        
        if(o.responseText !== undefined && o.responseText.indexOf("true") >= 0){ 
            window.location = WEBROOT + "/signedup-choose";
            
            //~ if(!referer || referer == "/" || referer == "")
                //~ window.location = WEBROOT + "/";
            //~ else
                //~ window.location = referer;
        } 
        
        else if(o.responseText !== undefined && (o.responseText.indexOf("captcha failed") >= 0)) {
            showAlert("Sorry, the security code you entered, was incorrect<br />Please try again.");
            $('#captcha').src = 'include/captcha/securimage_show.php?' + Math.random();
            frm.captcha_code.focus();
        }
        
        else if(o.responseText !== undefined && (o.responseText.indexOf("username taken") >= 0)) {
            showAlert("Sorry, the username you entered is already taken.<br />Please try again.");
            frm.username.focus();
        }
        
        else if(o.responseText !== undefined && (o.responseText.indexOf("email registered") >= 0)) {
            showAlert("Sorry, the email you entered is already registered with CoolProducts.<br />Please try again.");
            frm.email.focus();
        }
        
        else if(o.responseText !== undefined && (o.responseText.indexOf("empty field") >= 0)) {
            showAlert("Sorry, not all form fields were submitted.<br />Please try again.");
            frm.username.focus();
        }
        
        else if(o.responseText !== undefined && (o.responseText.indexOf("api") >= 0)) {
            showAlert("Sorry, we could not process your signup at this time.<br />Please try again or contact support. <support@coolproducts.com>");
            frm.username.focus();
        }
        
        else {
            showAlert("Sorry, we could not process your signup at this time.<br />Please try again or contact support. <support@coolproducts.com>");
            $('#signup-message').html("Sorry!");
        }
        
        // show loading indicator
        $('#global-loading').css("visibility", "hidden");
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    // make sure form is filled out correctly
    if(validateSignupForm(frm)) {
        // show loading indicator
        $('#global-loading').css("visibility", "visible");
        
        // get signup-form data to be submitted
        YAHOO.util.Connect.setForm(frm);
        
        // set notification message
        $('#signup-message').html("Attempting Signup...");
        
        // process signup-form
        var request = YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/processSignupForm.php', callback);
    }
}

/***********************************
* tell-a-friend-form submit event
*
* submits tell-a-friend-form data
* to backend processor.
************************************/
function submitTellAFriendForm(id) {
    var frm = $('#' + id)[0];
    
    var handleSuccess = function(o){ 
        // hide notification message
        $('#tell-a-friend-message').html("");
        
        if(o.responseText !== undefined && o.responseText.indexOf("true") >= 0){ 
            showAlert('Thanks! Your friend has been invited!');
            $('#tell-a-friend-message').html("Thanks!");
            frm.reset();
        } 
    
        else {
            showAlert("Sorry, we could not process your friend invitation at this time.<br />Please try again or contact support. <support@coolproducts.com>");
        }
        
        // hide loading indicator
        $('#global-loading').css("visibility", "hidden");
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    // make sure form is filled out correctly
    if(validateTellAFriendForm(frm)) {
        // show loading indicator
        $('#global-loading').css("visibility", "visible");
        
        // get tell-a-friend-form data to be submitted
        YAHOO.util.Connect.setForm(frm);
        
        // show sending
        $('#sending').css('display', 'inline');
        
        // process signup-form
        var request = YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/processTellAFriendForm.php', callback);
    }
}

/***********************************
* feedback-form submit event
*
* submits feedback-form data
* to backend processor.
************************************/
function submitFeedbackForm(id) {
    var frm = $('#' + id)[0];
    
    var handleSuccess = function(o){ 
        if(o.responseText !== undefined && o.responseText.indexOf("true") >= 0){ 
            showAlert('Thanks! Your feedback is greatly appreciated!');
            frm.reset();
        } 
    
        else if(o.responseText !== undefined && (o.responseText.indexOf("empty field") >= 0)) {
            showAlert("Sorry, not all form fields were submitted.<br />Please try again.");
            frm.feedback.focus();
        }
    
        else {
            showAlert("Sorry, we could not process your feedback at this time.<br />Please try again or contact support. <support@coolproducts.com>");
        }
        
        // show loading indicator
        $('#global-loading').css("visibility", "hidden");
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    // make sure form is filled out correctly
    if(validateFeedbackForm(frm)) {
        // show loading indicator
        $('#global-loading').css("visibility", "visible");
        
        // get feedback-form data to be submitted
        YAHOO.util.Connect.setForm(frm);
        
        // show sending
        $('#sending').css('display', 'inline');
        
        // process feedback-form
        var request = YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/processFeedbackForm.php', callback);
    }
}

/***********************************
* sent-to-a-friend-form submit event
*
* submits feedback-form data
* to backend processor.
************************************/
function submitSendToAFriendForm(id) {
    var frm = $('#' + id)[0];
    
    var handleSuccess = function(o){ 
        if(o.responseText !== undefined && o.responseText.indexOf("true") >= 0){ 
            showAlert('Congratulations! You have just told one of your friends about this cool product!');
        } 
    
        else if(o.responseText !== undefined && (o.responseText.indexOf("empty field") >= 0)) {
            showAlert("Sorry, not all form fields were submitted.<br />Please try again.");
            frm.feedback.focus();
        }
        
        else if(o.responseText !== undefined && (o.responseText.indexOf("product not found") >= 0)) {
            showAlert("Sorry, we could not send this product along at this time.<br />Please try again or contact support. <support@coolproducts.com>");
        }
    
        else {
            showAlert("Sorry, we could not send this product along at this time.<br />Please try again or contact support. <support@coolproducts.com>");
        }
        
        // show loading indicator
        $('#global-loading').css("visibility", "hidden");
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    // make sure form is filled out correctly
    if(validateSendToAFriendForm(frm)) {
        // show loading indicator
        $('#global-loading').css("visibility", "visible");
        
        // get send-to-a-friend-form data to be submitted
        YAHOO.util.Connect.setForm(frm);
        
        // show sending
        $('#sending').css('display', 'inline');
        
        // process send-to-a-friend-form
        var request = YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/processSendToAFriendForm.php', callback);
    }
}

/***********************************
* suggest-form submit event
*
* submits suggest-form data to backend processor.
************************************/
function submitSuggestForm(id) {
    var frm = $('#' + id)[0];
    
    var handleSuccess = function(o){         
        if(o.responseText !== undefined && o.responseText.indexOf("true") >= 0){ 
            // everything went ok
            showAlert("Your Product Has Been Submitted!");
            resetSuggestForm("suggest-form");
            $('#suggest-message').html("<h3>Thanks!</h3><h3>Your product will be moderated and potentially posted in the next 24-48hrs</h3>");
        } 
        
        else if(o.responseText !== undefined && (o.responseText.indexOf("user user not logged in") >= 0)) {
            showAlert("Sorry, you must be logged in to suggest a product.");
            openModalWindow(WEBROOT + "/html/modal/loginForm.htm", null, "Please Login");
        }
        
        else if(o.responseText !== undefined && (o.responseText.indexOf("empty field") >= 0)) {
            showAlert("Sorry, one of the fields were empty");
            frm.name.focus();
        }
        
        else if(o.responseText !== undefined && (o.responseText.indexOf("user does not exist") >= 0)) {
            showAlert("Sorry, your product could not be processed at this time.<br />Please try again or contact support. <support@coolproducts.com>");
            $('#suggest-message').html("Sorry!");
        }
        
        else if(o.responseText !== undefined && (o.responseText.indexOf("api failed") >= 0)) {
            showAlert("Sorry, your product could not be processed at this time.<br />Please try again or contact support. <support@coolproducts.com>");
            $('#suggest-message').html("Sorry!");
        }
        
        else {
            showAlert("Sorry, your product could not be processed at this time.<br />Please try again or contact support. <support@coolproducts.com>");
            $('#suggest-message').html("Sorry!");
        }
        
        // hide loading indicator
        $('#global-loading').css("visibility", "hidden");
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    // make sure form is filled out correctly
    if(validateSuggestForm(frm)) {
        // show loading indicator
        $('#global-loading').css("visibility", "visible");
        
        // get contact-form data to be submitted
        YAHOO.util.Connect.setForm(frm);
        
        // set page to "loading"
        $('#suggest-message').html("<b>Submitting Product...<b>");
        
        // process contact-form
        var request = YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/processSuggestForm.php', callback);
    }
}

/***********************************
* comment-form submit event
*
* submits comment-form data to backend processor.
************************************/
function submitProductCommentForm(id) {
    var frm = $('#' + id)[0];
    
    $('#comment-form-message').html("<b>submitting...</b>");
    
    var handleSuccess = function(o){         
        $('#comment-form-message').html("");
        
        if(o.responseText !== undefined && o.responseText.indexOf("true") >= 0){ 
            // everything went ok, slide the form up and then add the comment to the DOM
            toggleProductCommentForm();
            addProductComment();
            frm.reset();
        } 
        
        else if(o.responseText !== undefined && (o.responseText.indexOf("captcha failed") >= 0)) {
            showAlert("captcha failed");
            frm.captcha.focus();
        }
        
        else if(o.responseText !== undefined && (o.responseText.indexOf("empty field") >= 0)) {
            showAlert("Sorry, one of the fields were empty");
            frm.comment.focus();
        }
        
        else if(o.responseText !== undefined && (o.responseText.indexOf("user not logged in") >= 0)) {
            showAlert("Sorry, you must login before posting comments");
        }
        
        else if(o.responseText !== undefined && (o.responseText.indexOf("api failed") >= 0)) {
            showAlert("Sorry, your comment could not be processed at this time.<br />Please try again or contact support. <support@coolproducts.com>");
        }
        
        else {
            showAlert("Sorry, your comment could not be processed at this time.<br />Please try again or contact support. <support@coolproducts.com>");
        }
        
        // hide loading indicator
        $('#global-loading').css("visibility", "hidden");
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    // make sure form is filled out correctly
    if(validateCommentForm(frm)) {
        // show loading indicator
        $('#global-loading').css("visibility", "visible");
        
        // get comment-form data to be submitted
        YAHOO.util.Connect.setForm(frm);
        
        // process comment-form
        var request = YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/processProductCommentForm.php', callback);
    }
}

/***********************************
* change-password-form submit event
*
* submits change-password-form data to backend processor.
************************************/
function submitChangePasswordForm(id) {
    var frm = $('#' + id)[0];
    
    $('#change-password-message').html("");
    
    var handleSuccess = function(o){         
        if(o.responseText !== undefined && o.responseText.indexOf("true") >= 0){ 
            showAlert('your password has been successfully changed');
        } 
        
        else if(o.responseText.indexOf("password wrong") >= 0) {
            $('#change-password-message').html("Invalid password");
            frm.opw.focus();
        }
        
        else
            showAlert("Sorry, we could not change your password at this time.<br />Please try again or contact support. <support@coolproducts.com>");
            
        // show loading indicator
        $('#global-loading').css("visibility", "hidden");
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    // make sure form is filled out correctly
    if(validateChangePasswordForm(frm)) {
        // show loading indicator
        $('#global-loading').css("visibility", "visible");
        
        // get change-password-form data to be submitted
        YAHOO.util.Connect.setForm(frm);
            
        // process change-password-form
        var request = YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/processChangePasswordForm.php', callback);
    }
}

/***********************************
* change-email-form submit event
*
* submits change-email-form data to backend processor.
************************************/
function submitChangeEmailForm(id) {
    var frm = $('#' + id)[0];
    
    $('#change-email-message').html("");
    
    var handleSuccess = function(o){         
        if(o.responseText !== undefined && o.responseText.indexOf("true") >= 0) { 
            showAlert('your email address has been successfully updated to ' + frm.nemail.value);
        } 
        
        else if(o.responseText.indexOf("email already registered") >= 0) { 
            showAlert("Sorry, the email you entered is already registered at CoolProducts.<br />Please try again.");
            frm.nemail.focus();
        }
        
        else if(o.responseText.indexOf("user does not exist") >= 0) { 
            showAlert("Sorry, we could not find anyone with that email address.<br />Please try again.");
            frm.oemail.focus();
        }
        
        else if(o.responseText.indexOf("same email") >= 0) { 
            showAlert("Sorry, the email address you entered is the same as your current email address.<br />Please try again.");
            frm.nemail.focus();
        }
        
        else if(o.responseText.indexOf("email wrong") >= 0) { 
            $('#change-email-message').html("Incorrect current email");
            frm.oemail.focus();
        }
        
        else
            showAlert("Sorry, we could not change your email at this time.<br />Please try again or contact support. <support@coolproducts.com>");
            
        // show loading indicator
        $('#global-loading').css("visibility", "visible");
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    // make sure form is filled out correctly
    if(validateChangeEmailForm(frm)) {
        // show loading indicator
        $('#global-loading').css("visibility", "visible");
        
        // get change-email-form data to be submitted
        YAHOO.util.Connect.setForm(frm);
        
        // process comment-form
        var request = YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/processChangeEmailForm.php', callback);
    }
}

/***********************************
* contest-registration-form submit event
*
* submits contest-registration-form data 
* to backend processor.
************************************/
function submitContestRegistrationForm(id) {
    var frm = $('#' + id)[0];
    
    // reset status message
    $('#contest-registration-message').html("");
    
    var handleSuccess = function(o){         
        if(o.responseText !== undefined && o.responseText.indexOf("true") >= 0) { 
            showAlert('You have successfully been entered into the contest');
            $('#contest-registration-message').html("Thanks!");
            frm.reset();
        } 
        
        else if(o.responseText.indexOf("already registered") >= 0) { 
            showAlert("Our records indicate that you are already registered for this contest. You're good to go!");
            $('#contest-registration-message').html("");
            frm.reset();
        }

        else if(o.responseText !== undefined && (o.responseText.indexOf("empty field") >= 0)) {
            showAlert("Sorry, not all form fields were submitted.<br />Please try again.");
            $('#contest-registration-message').html("Please Try Again");
        }

        else if(o.responseText !== undefined && (o.responseText.indexOf("email to contest participant failed") >= 0)) {
            showAlert("Sorry, we could not register you for our contest at this time.<br />Please try again or contact support. <support@coolproducts.com>");
            $('#contest-registration-message').html("");
        }

        else {
            showAlert("Sorry, we could not register you for our contest at this time.<br />Please try again or contact support. <support@coolproducts.com>");
            $('#contest-registration-message').html("");
        }
        
        // show loading indicator
        $('#global-loading').css("visibility", "hidden");
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    // make sure form is filled out correctly
    if(validateContestRegistrationForm(frm)) {
        // show loading indicator
        $('#global-loading').css("visibility", "visible");
        
        // set status message
        $('#contest-registration-message').html("Registering...");
        
        // get contest-registration-form data to be submitted
        YAHOO.util.Connect.setForm(frm);
        
        // process contest-registration-form
        var request = YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/processContestRegistrationForm.php', callback);
    }
}

/***********************************
* contest-question-form submit event
*
* submits contest-question-form data 
* to backend processor.
************************************/
function submitContestQuestionsForm(id) {
    var frm = $('#' + id)[0];
        
    // reset status message
    $('#contest-questions-message').html("");
    
    var handleSuccess = function(o){         
        if(o.responseText !== undefined && o.responseText.indexOf("true") >= 0) { 
            showAlert('Your questions have been successfully submitted.<br />Thanks! We\'ll get back to you as soon as possible');
            $('#contest-questions-message').html("Thanks!");
            frm.reset();
        } 
        
        else if(o.responseText !== undefined && (o.responseText.indexOf("empty field") >= 0)) {
            showAlert("Sorry, not all form fields were submitted.<br />Please try again.");
            frm.name.focus();
        }
        
        else
            showAlert("Sorry, we could not process your questions at this time.<br />Please try again or contact support. <support@coolproducts.com>");
            
        // show loading indicator
        $('#global-loading').css("visibility", "hidden");
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    // make sure form is filled out correctly
    if(validateContestQuestionsForm(frm)) {
        // show loading indicator
        $('#global-loading').css("visibility", "visible");
        
        // set status message
        $('#contest-questions-message').html("Sending...");
        
        // get contest-registration-form data to be submitted
        YAHOO.util.Connect.setForm(frm);
        
        // process contest-questions-form
        var request = YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/processContestQuestionsForm.php', callback);
    }
}

/***********************************
* commissions-question-form submit event
*
* submits contest-question-form data 
* to backend processor.
************************************/
function submitCommissionsQuestionsForm(id) {
    var frm = $('#' + id)[0];
        
    // reset status message
    $('#commissions-questions-message').html("");
    
    var handleSuccess = function(o){         
        if(o.responseText !== undefined && o.responseText.indexOf("true") >= 0) { 
            showAlert('Your questions have been successfully submitted.<br />Thanks! We\'ll get back to you as soon as possible');
            $('#commissions-questions-message').html("Thanks!");
            frm.reset();
        } 
        
        else if(o.responseText !== undefined && (o.responseText.indexOf("empty field") >= 0)) {
            showAlert("Sorry, not all form fields were submitted.<br />Please try again.");
            frm.name.focus();
        }
        
        else
            showAlert("Sorry, we could not process your questions at this time.<br />Please try again or contact support. <support@coolproducts.com>");
        
        // show loading indicator
        $('#global-loading').css("visibility", "hidden");
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    // make sure form is filled out correctly
    if(validateCommissionsQuestionsForm(frm)) {
        // show loading indicator
        $('#global-loading').css("visibility", "visible");
        
        // set status message
        $('#commissions-questions-message').html("Sending...");
        
        // get contest-registration-form data to be submitted
        YAHOO.util.Connect.setForm(frm);
        
        // process contest-questions-form
        var request = YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/processCommissionsQuestionsForm.php', callback);
    }
}

/***********************************
* checkUsernameAvailability event
*
* Checks the given username to determine 
* if it has been taken
************************************/
function checkUsernameAvailability() {
    var username = $('#signup-form')[0].username.value;
    
    var handleSuccess = function(o){
        if(o.responseText !== undefined && o.responseText.indexOf("available") >= 0)
            $('#available').html("<img style='margin-bottom:-2px' src='images/check.gif' />available");
        
        else if(o.responseText !== undefined && o.responseText.indexOf("taken") >= 0) 
            $('#available').html("<img style='margin-bottom:-2px' src='images/x.gif' />taken");
            
        else {
            showAlert("Sorry this feature is broken right now, we're working to fix it as soon as possible :-0");
            $('#available').html("Sorry!");
        }
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    // check username availability
    if(jQuery.trim(username) != '') {
        // show "checking..." status 
        $('#available').html("checking...");
        var data = 'u=' + username;
        var request = YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/checkUsernameAvailability.php', callback, data);
    }
    else {
        $('#available').html("");
    }
}

/***********************************
* checkUserLoginStatus event
*
* Makes a call to the back-end to 
* determine whether the current user
* is logged in or not to determine
* if they can suggest or not.
* 
* @param cb - callback object
************************************/
function checkUserLoginStatus(cb) {
    var handleSuccess = function(o){
        if(o.responseText !== undefined && o.responseText.indexOf("true") >= 0)
            cb.success();
        
        else if(o.responseText !== undefined && o.responseText.indexOf("false") >= 0) 
            cb.failure();
            
        else {
            showAlert("Sorry this feature is broken right now, we're working to fix it as soon as possible :-0");
        }
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/checkUserLoginStatus.php', callback);

}

/***********************************
* getSubCategoryMarkup event
*
* Makes a call to the back-end to 
* retrieve the markup for those categories
* below the given category id. Puts result
* in a div identified by level
* 
* @param category_id - category_id
* @param level - level to place result in
************************************/
function getSubCategoryMarkup(category_id, level) {
    var prev_level = level - 1;
    
    // change the go-to-category and surprise-me buttons back to normal state
    $('#go-to-category, #surprise-me').css('background-color', '#dcddde');
    $('#go-to-category, #surprise-me').css('color', '#333133');
    
    // clear the other levels
    for (i = level; i <= 3; i++)
        $('#category-selection-level' + i).html("");
        
    // un-select all categories at the previous level
    $('#category-selection-level' + prev_level + ' > ul > li').removeClass();
    
    // set this category_id to selected
    $('#category-' + category_id).addClass("selected-category");
    
    // reset the category-name contents
    $('#category-name').html("<i>Please Select A Category Below</i>");
    
    // reset the form's category_id hidden field
    $('.category-selection-form')[0].category_id.value = 0;
    
    // show loading
    $('#category-selection-level' + level).html("loading subcategories...");
    
    var handleSuccess = function(o){
        if(o.responseText !== undefined && o.responseText.indexOf("false - error: category_id not posted") >= 0) 
            $('#category-selection-level' + level).html("No subcategories found!");
            
        else if(o.responseText !== undefined && o.responseText.indexOf("false - error: level not posted") >= 0) 
            $('#category-selection-level' + level).html("No subcategories found!");
            
        else
            $('#category-selection-level' + level).html(o.responseText);
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    var data = "category_id=" + category_id + '&level=' + level;
    YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/getCategorySelectionMarkup.php', callback, data);

}

/***********************************
* gotoSignup event
*
* Makes sure user is redirected to 
* correctly formed signup url
************************************/
function gotoSignup() {
    window.location = WEBROOT + "/signup";
}

/***********************************
* vote submit event
*
* submits product vote to backend processor.
************************************/
function submitProductVote(gift_id, variable_id, vote_value) {
    var handleSuccess = function(o){         
        if(o.responseText !== undefined && o.responseText.indexOf("true") >= 0) { 
            // everything went ok, indicate to the user that the vote was successful -- switch images or something
            updateVoteButton(gift_id, variable_id, vote_value);
        }
        
        else if(o.responseText.indexOf("invalid user") >= 0) {
            showAlert("Sorry, you must be logged in to vote on a product", 'window.location="'+WEBROOT+'/login"');
        }
        
        else if(o.responseText !== undefined && (o.responseText.indexOf("api failed") >= 0)) {
            showAlert("Sorry, Your vote could not be processed at this time.<br />Please try again or contact support. <support@coolproducts.com>");
        }
        
        else {
            showAlert("Sorry, Your vote could not be processed at this time.<br />Please try again or contact support. <support@coolproducts.com>");
        }
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    var data = "gift_id=" + gift_id + "&variable_id=" + variable_id + "&vote_value=" + vote_value;
    YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/processProductVote.php', callback, data);
}

/***********************************
* delete vote event
*
* deletes a product vote.
************************************/
function deleteProductVote(gift_id, variable_id) {
    var handleSuccess = function(o){         
        if(o.responseText !== undefined && o.responseText.indexOf("true") >= 0) { 
            // everything went ok, indicate to the user that the vote was successful -- switch images or something
            resetVoteToolbar(gift_id, variable_id);
        }
        
        else if(o.responseText.indexOf("invalid user") >= 0) {
            showAlert("Sorry, you must be logged in to vote on a product", 'window.location="'+WEBROOT+'/login"');
        }
        
        else if(o.responseText !== undefined && (o.responseText.indexOf("api failed") >= 0)) {
            showAlert("Sorry, Your vote could not be processed at this time.<br />Please try again or contact support. <support@coolproducts.com>");
        }
        
        else {
            showAlert("Sorry, Your vote could not be processed at this time.<br />Please try again or contact support. <support@coolproducts.com>");
        }
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    var data = "gift_id=" + gift_id + "&variable_id=" + variable_id;
    YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/deleteProductVote.php', callback, data);
}

/***********************************
* add to favorites event
*
* adds a product to a user's favorites
************************************/
function addToFavorites(product_id) {
    var handleSuccess = function(o){
        if(o.responseText !== undefined && o.responseText.indexOf("true") >= 0) { 
            // everything went ok, indicate to the user that the vote was successful -- switch images or something
            updateAddToFavoritesButton(product_id);
        }
        
        else if(o.responseText.indexOf("user does not exist") >= 0) {
            showAlert("Sorry, you must be logged in to save products to your favorites", 'window.location="'+WEBROOT+'/login"');
        }
        
        else if(o.responseText !== undefined && (o.responseText.indexOf("api failed") >= 0)) {
            showAlert("Sorry, We could not save this product to your favorites at this time.<br />Please try again or contact support. <support@coolproducts.com>");
        }
        
        else {
            showAlert("Sorry, We could not save this product to your favorites at this time.<br />Please try again or contact support. <support@coolproducts.com>");
        }
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    var data = "pid=" + product_id + "&ref=products";
    YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/addToFavorites.php', callback, data);
}

/***********************************
* reportProductComment event
*
* Makes a call to the back-end and
* generates a notification email
* about the product comment in question
************************************/
function reportProductComment(comment_id) {
    var handleSuccess = function(o){
        // always tell user it succeeded, unless it's just broken all together
        if(o.responseText !== undefined)
            $('#report-this-'+comment_id).html("<div class='reported'>*reported*</div>");
        else
            showAlert("Sorry this feature is broken right now, we're working to fix it as soon as possible :-0");
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    var data = "cid=" + comment_id;
    YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/processProductCommentReport.php', callback, data);
}

/***********************************
* linkToIfLoggedIn
*
* A DOM manipulation that either links
* correctly to the url that is passed
* in or shows a modal message window
* telling the user they must first
* login before they can link to this
* item.
************************************/
function linkToIfLoggedIn(href) {
    var afterAlert = 'window.location = "' + WEBROOT + '/login";';
    var handleSuccess = function(){ window.location = WEBROOT + href; }
    var handleFailure = function(){ showAlert('Please login before proceeding', afterAlert); };
    
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    // do the magic based on the user's login status
    checkUserLoginStatus(callback);
}

/***********************************
* doIfLoggedIn
*
* A DOM manipulation that either executes
* the callback function or shows a modal 
* message window telling the user they 
* must first login before they can 
* perform an action.
************************************/
function doIfLoggedIn(f) {
    var afterAlert = 'window.location = "' + WEBROOT + '/login";';
    var handleSuccess = function(){ f(); }
    var handleFailure = function(){ showAlert('Please login before proceeding', afterAlert); };
    
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    // do the magic based on the user's login status
    checkUserLoginStatus(callback);
}

/***********************************
* set product sort event
*
* Sets a cookie that determines product
* sort order
************************************/
function setProductSort() {
    var sort_by = $('#sort-by-form')[0].sortby.value;
    
    var handleSuccess = function(o){         
        // reload the page no matter what
        window.location.reload();
        
        //~ if(o.responseText !== undefined && o.responseText.indexOf("true") >= 0) { 
            //~ // everything went ok
            //~ window.location.reload();
        //~ }
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    var data = "sort=" + sort_by;
    YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/setProductSort.php', callback, data);
}

/***********************************
* set product sort event
*
* Sets a session variable that contains
* a product name. Currently being used
* in the processSendToAFriendForm handler
************************************/
function setProductName(product_name) {
    var handleSuccess = function(o){         
        // true -- graceful
    }
    var handleFailure = function() { /*showAlert('Request Failed');*/ }
    var callback = { success:handleSuccess, failure: handleFailure }; 
    
    var data = "pn=" + product_name;
    YAHOO.util.Connect.asyncRequest('POST', WEBROOT + '/actions/setProductName.php', callback, data);
}
