/* This file handles future bids */
var FutureBidsLeft = -1;
var UserID = -1;
var AuctionID = -1;
var StartingPrice = -1;
var EndingPrice = -1;
var DeletedOnce = false;
var DefaultInputBorder;
var ErrorInputBorder;

jQuery.noConflict(); // When you call .noConflict() jQuery will return $() to it’s previous owner and you will need to use jQuery() instead of shorthand $() function.
jQuery(document).ready(function(){

    initialize();

    jQuery('button.deleteFutureBids').click(function(){
        deleteFutureBids();
    });

    jQuery('#futurebids input#submit').click(function(){
        saveFutureBids();
    });

    onKeyUp(); //validates on key up

}); /* end ready */


function getRemainingFutureBids(){
    if(UserID >= 0 && AuctionID >= 0){
        var getFutureBidsURL = '/FutureBids.php?action=1&user_id='+UserID+'&auction_id='+AuctionID;
        jQuery.ajax({
            url: getFutureBidsURL,
            dataType: 'json',
            type: 'GET',
            timeout: 2999,
            global: false,
            cache: false,
            success: function(data){
                StartingPrice = data.minimum_price;
                EndingPrice = data.maximum_price;
                FutureBidsLeft = data.bids;
                displayRemainingFutureBids();
            },
            error: function(){

            }
        });
    }
}

function deleteFutureBids(){
    if(UserID >= 0 && AuctionID >= 0){
        var getFutureBidsURL = '/FutureBids.php?action=2&user_id='+UserID+'&auction_id='+AuctionID;
        jQuery.ajax({
            url: getFutureBidsURL,
            dataType: 'text',
            type: 'GET',
            timeout: 2999,
            global: false,
            cache: false,
            success: function(data){
                //alert('deleted futurbids for '+UserID+' and '+AuctionID);
                FutureBidsLeft = -1;
                displayRemainingFutureBids();
                jQuery('input.required').val('');
                jQuery("#minimum").focus();
                jQuery('#futurebids label.errMsg').hide();
            },
            error: function(){

            }
        });
    }
}

function saveFutureBids(){
    //alert('minval = '+minVal+ 'maxVal = '+maxVal+'bids = '+bids+'userID = '+UserID+' auctionID = '+AuctionID);
    if(UserID >= 0 && AuctionID >= 0){
        var minVal = (+jQuery('#futurebids input#minimum').val()).toFixed(2);
        var maxVal = (+jQuery('#futurebids input#maximum').val()).toFixed(2);
        var bids = jQuery('#futurebids input#bids').val();

        if (validateFutureBids(minVal, maxVal, bids) == false) {
            return false;
        } else {
            //alert('minval = '+minVal+ 'maxVal = '+maxVal+'bids = '+bids+'userID = '+UserID+' auctionID = '+AuctionID);
            var getFutureBidsURL = '/FutureBids.php?action=3&user_id='+UserID+'&auction_id='+AuctionID+'&minVal='+minVal+'&maxVal='+maxVal+'&bids='+bids;
            jQuery.ajax({
                url: getFutureBidsURL,
                dataType: 'text',
                type: 'GET',
                timeout: 2999,
                global: false,
                cache: false,
                success: function(data){
                    //alert('saved futurbids for '+UserID+' and '+AuctionID);
                    StartingPrice = minVal;
                    EndingPrice = maxVal;
                    FutureBidsLeft = bids;
                    displayRemainingFutureBids();
                },
                error: function(){

                }
            });
            return true;
        }
    }
    return false;
}

function displayRemainingFutureBids(){

    if(FutureBidsLeft <= 0 || FutureBidsLeft == undefined){
        if (DeletedOnce == false) {
            jQuery('#deleteFutureBidFields').hide();
            jQuery('.futurebidsform').show();

            deleteFutureBids();
            DeletedOnce = true;
        }
    } else {
        StartingPrice = (+StartingPrice).toFixed(2);
        EndingPrice = (+EndingPrice).toFixed(2);

        jQuery('.displayStartingPrice').html('<p>Starting at: $<span>' + StartingPrice +'</span></p>');
        jQuery('.displayEndingPrice').html('<p>Ending at: $<span>' + EndingPrice +'</span></p>');
        jQuery('.displayRemainingFutureBids').html('<p>You have... <span id = "futurebidsleft">' + FutureBidsLeft + '</span> ...Future Bids remaining.</p>');

        jQuery('.futurebidsform').hide();
        jQuery('#deleteFutureBidFields').show();

        DeletedOnce = false;
        //alert(FutureBidsLeft);
    }

}

function validateFutureBids(minVal, maxVal, bids){
    var bResult = true;

    minVal = +minVal;
    maxVal = +maxVal;
    bids = +bids;

    jQuery('#futurebids label.errMsg').hide();
    jQuery('#futurebids input.required').css('border', DefaultInputBorder);

    if (minVal <= 0 || isNaN(minVal)){
       jQuery('#futurebids label.errMsg#minimum').show();
       jQuery('#futurebids input.required#minimum').css('border', ErrorInputBorder);
       bResult = false;
    }

    if (maxVal <= 0 || isNaN(maxVal)){
       jQuery('#futurebids label.errMsg#maximum').show();
       jQuery('#futurebids input.required#maximum').css('border', ErrorInputBorder);
       bResult = false;
    }

    if (bids <= 0 || !isPositiveInteger(bids) || isNaN(bids)){
       jQuery('#futurebids label.errMsg#bids').show();
       jQuery('#futurebids input.required#bids').css('border', ErrorInputBorder);
       bResult = false;
    }

    if (bResult == true && maxVal <= minVal){
       jQuery('#futurebids label.errMsg#maxCompare').show();
       jQuery('#futurebids input.required#maximum').css('border', ErrorInputBorder);
       bResult = false;
    }

    return bResult;
}

function isPositiveInteger(sText){
   var validChars = "0123456789";
   var isNumber = true;
   var cChar;

   for (i = 0; i < sText.length && isNumber == true; i++)
   {
      cChar = sText.charAt(i);
      if (validChars.indexOf(cChar) == -1)
      {
         isNumber = false;
      }
   }

   return isNumber;
}

function onKeyUp(){

    jQuery('#futurebids input.required#minimum').keyup(function(event){
        if (event.keyCode != 9) {

            var minVal = (+jQuery('#futurebids input.required#minimum').val()).toFixed(2);
            if (minVal <= 0 || isNaN(minVal)){
                jQuery('#futurebids label.errMsg#minimum').show();
                jQuery('#futurebids input.required#minimum').css('border', ErrorInputBorder);
            } else {
                jQuery('#futurebids label.errMsg#minimum').hide();
                jQuery('#futurebids input.required#minimum').css('border', DefaultInputBorder);
            }

        }
    });

    jQuery('#futurebids input.required#maximum').keyup(function(event){
        if (event.keyCode != 9) {                  // # 9 is the TAB key

            var maxVal = (+jQuery('#futurebids input.required#maximum').val()).toFixed(2);
            var minVal = (+jQuery('#futurebids input.required#minimum').val()).toFixed(2);
            if (maxVal <= 0 || isNaN(maxVal)){
                jQuery('#futurebids label.errMsg#maximum').show();
                jQuery('#futurebids input.required#maximum').css('border', ErrorInputBorder);
            } else {
                jQuery('#futurebids label.errMsg#maximum').hide();
                jQuery('#futurebids input.required#maximum').css('border', DefaultInputBorder);
            }

            if (maxVal > minVal){
                jQuery('#futurebids label.errMsg#maxCompare').hide();
                jQuery('#futurebids input.required#maximum').css('border', DefaultInputBorder);
            }

        }
    });

    jQuery('#futurebids input.required#bids').keyup(function(event){
        if (event.keyCode != 9) {

            var bids = (+jQuery('#futurebids input.required#bids').val());
            if (bids <= 0 || !isPositiveInteger(bids) || isNaN(bids)){
                jQuery('#futurebids label.errMsg#bids').show();
                jQuery('#futurebids input.required#bids').css('border', ErrorInputBorder);
            } else {
                jQuery('#futurebids label.errMsg#bids').hide();
                jQuery('#futurebids input.required#bids').css('border', DefaultInputBorder);
            }

        }
    });

}

function initialize(){
    DefaultInputBorder = '1px solid blue';
    ErrorInputBorder = '2px solid red';

    jQuery("#minimum").focus();

    jQuery('#futurebids input.required').css('border', DefaultInputBorder);

    jQuery('.futureBidClueTip').cluetip({
        ajaxCache:     true,
        splitTitle:    '|',
        arrows:        true,
        width:         600
    });

    jQuery('.MSRPClueTip').cluetip({
        ajaxCache:     true,
        splitTitle:    '|',
        arrows:        true,
        width:         260
    });

    jQuery('a.localtip').cluetip({
        ajaxCache:     true,
        arrows:        true,
        local:         true,
        width:         625
    });
}

function setUserID(id){
    UserID = id;
}

function setAuctionID(id){
    AuctionID = id;
}

function setStartingPrice(price){
    StartingPrice = price;
}

function setEndingPrice(price){
    EndingPrice = price;
}

function getUserID(){
    //alert('userid = '+UserID);
}

function getAuctionID(){
    //alert('auctionid = '+AuctionID);
}

function getFutureBidsLeft(){
    return FutureBidsLeft;
}

function setFutureBidsLeft(bids){
    FutureBidsLeft = bids;
}

//***  The following code is from a validate plug-in. *****************************************************************
//*******************************************************************************************************************
    //Had to write the greaterThan, lessThan, and positiveNumber functions because they are not in the library YET!

/*
    jQuery.validator.addMethod('greaterThan', function (value, element, param){
        return value > $(param).val();
    }, 'Message');

    jQuery.validator.addMethod('lessThan', function (value, element, param){
        return value < $(param).val();
    }, 'Message');

    jQuery.validator.addMethod('positiveNumber', function (value, element, param){
        return value > 0;
    }, 'Message');
*/

  /*
  jQuery('#futurebids').validate({
   rules: {
     minimum: {
        required: true,
	positiveNumber: true,
        number: true
     },
     maximum: {
        required: true,
	positiveNumber: true,
        number: true
	//greaterThan: '#minimum'
     },
     bids: {
        required: true,
        digits: true
     }
   }, //end rules
   messages: {
     minimum: {
        required: "Please enter a number.",
	positiveNumber: "Please enter a positive number."
     },
     maximum: {
        required: "Please enter a number.",
	positiveNumber: "Please enter a positive number.",
	greaterThan: 'Maximum price must be greater than minimum price.'
     },
     bids: {
        required: "Please enter a number.",
	digits: "Please enter a positive whole number."
     }
   }, //end messages
   errorPlacement: function(error, element) {
          //error.appendTo( element.parent());
          error.insertAfter(element);
    }

  }); // end validate
 */
//***  The above code is from a validate plug-in. *************************************************