// Popup front-end code

// This code needs to be refactored to consolidate all the similar routines

// AJAX Functions
// Functions are all seperate so we could do different funky stuff with each

var ajax_auction_loading = false;
var ajax_bid_loading = false;
var ajax_other_loading = false;

function ajax_auctions_loading(on) {
   if (on) {
      ajax_auction_loading = true;
      // do funky stuff here
   } else {
      // clear funky stuff here
      ajax_auction_loading = false;
   }
}

function ajax_bids_loading(on) {
   if (on) {
      ajax_bid_loading = true;
      // do funky stuff here
   } else {
      // clear funky stuff here
      ajax_bid_loading = false;
   }
}

//Ajax.Responders.register({
//    onCreate: function(){ Element.show('spinner')},
//    onComplete: function(){Element.hide('spinner')}
//});

function ajax_others_loading(on) {
   if (on) {
      ajax_other_loading = true;
      // do funky stuff here
   } else {
      // clear funky stuff here
      ajax_other_loading = false;
   }
}

function ajax_auction_request( in_auction ) {

   // retreive form data
   var auction_id = jQuery("input#formauctionid").val(); 
   var currencysymbol = jQuery("input#currencysymbol").val();

   if (ajax_auction_loading) return false;
   
   ajax_auctions_loading ( true );
   
   // new jQuery AJAX routine
   jQuery.ajax ({
      cache: false,
      type: "POST",
      url: 'http://lawtonphil.com/site-content/plugins/wp-auctions/wp_auctions.php?queryauction',
      data : {
         auction_ID : auction_id,
         _ajax_nonce: 'f251227d8b'
      },
      error: function(request,textStatus,errorThrown) {
	    alert((request.status!=406? ' WP_Auction Error '+request.status+' : '+request.statusText+'\n' : '')+request.responseText);
      },
   success: function(request, status) {
	    ajax_auctions_loading(false);   
	    if (status!="success") alert (status);  //"return"
	    	    
	    // update auction on screen
	    auction_details = request.split('|');
	    	    
	    // v4 started here	    

     // let's do this first
	    
	    jQuery('#wpa-popupid').val(auction_id);
	    jQuery('#engine').val(auction_details[20]);

      jQuery("#wpa-button-bids").show();
	    
      // first let's check if auction is open
      if (auction_details[8] == 0 || auction_details[22] == 0) {
         // auction is closed     
         jQuery("#wpa-button-bid").hide();
         jQuery("#wpa-button-bin").hide();      
	       winningbid_message = currencysymbol+auction_details[10];
      } else {
         // auction is open
         jQuery("#wpa-button-bid").show();
	       winningbid_message = "Open";
         
         // if auction has no BIN we should hide the section
         BIN_price = auction_details[11];
         if (BIN_price == 0) {
            jQuery("#wpa-button-bin").hide();           
         } else {
            jQuery("#wpa-button-bin").show();
            
            // check for BIN only
            if (auction_details[6] == 0) {
               jQuery("#wpa-button-bid").hide();
               jQuery("#wpa-button-bids").hide();
            }
         }     
      }
 	    
	    // description pane *****************************
	    
	    // prepare details
      reserve_message = "N/A";
      reserve_secondary_message = "N/A";
      if ( auction_details[19] > 0 ) {
         if ( (auction_details[19] * 1) > (auction_details[3] * 1)) { // cast to compare as numeric 
            reserve_message = "Reserve not met";
            reserve_secondary_message = "Not met";
         } else {
            reserve_message = "Reserve met";
            reserve_secondary_message = "Met";
         }
      }
	    
	    shippingto_message = ( auction_details[17] == "" ) ? "N/A" : auction_details[17];
	    shippingfrom_message = ( auction_details[21] == "" ) ? "N/A" : auction_details[21];
	    
	    // present details
	    
	    // do we have a category
	    category_message = "";
	    if (auction_details[24] != "") {
	       category_message = "<p><strong>Category:</strong> " + auction_details[24] + "</p>";
	    }
	    
	    jQuery('#wpa-description-title').html(auction_details[1]);
      jQuery('#wpa-description-p').html(category_message + auction_details[2]);            
      jQuery('#wpa-description-reserve').html(reserve_message);
      jQuery('#wpa-description-starting').html(currencysymbol+auction_details[6]);
      if ( auction_details[23] != "" ) {
         jQuery('#wpa-description-shipping').html(auction_details[23]);
      } else {
         if ( auction_details[16] == 0 ) {
            jQuery('#wpa-description-shipping').html("N/A");
         } else {
            jQuery('#wpa-description-shipping').html(currencysymbol+auction_details[16]);
         }
      }
      jQuery('#wpa-description-shippingto').html(shippingto_message);
      jQuery('#wpa-description-shippingfrom').html(shippingfrom_message);
	    jQuery('#wpa-description-winningbid').html(winningbid_message);

	    // bid pane *****************************
	    
	    // prepare details
	    currentbid_message = ( auction_details[3] == "" ) ? "No bids yet" : currencysymbol + auction_details[3];
	    
	    switch ( auction_details[20] ) {
	       case "1": // standard engine
	          maximumbid_message = "Enter Your Maximum Bid";
	          bidhigher_message = "Bid " + currencysymbol + auction_details[15] + " or higher";
	          break;
	       case "2": // simple engine
	          maximumbid_message = "Enter Your Bid";
	          bidhigher_message = "Bid " + currencysymbol + auction_details[15] + " or higher";
	          break;
	       case "3": // reverse engine
	          maximumbid_message = "Enter Your Bid";
	          bidhigher_message = "Bid " + currencysymbol + auction_details[15] + " or lower";	          
	          break;
	       default:
	          maximumbid_message = "WARNING: Auction type not defined";
	          bidhigher_message = "WARNING: Auction type not defined";
	    }
	    
	    // present details
	    jQuery('#wpa-currentbid').html(currentbid_message);
	    jQuery('#wpa-currentbidreserve').html(reserve_secondary_message);
	    jQuery('#wpa-currentbidending').html(auction_details[5]);
	    // #wpa-currentbidwinner populated by bid call	    
	    	    
	    jQuery('#wpa-maximumbid').html(maximumbid_message);
	    jQuery('#wpa-bidhigher').html(bidhigher_message);
	    jQuery('#wpa-currencysymbol').html(currencysymbol);
	    jQuery('#wpa-currencysymbolbin').html(currencysymbol);

      // bin pane *****************************

      if (BIN_price != 0) {
         jQuery('#wpa-currencysymbolbin').html(currencysymbol);
         jQuery("input#wpa-popbin").val( BIN_price );
         jQuery("input#wpa-popbin").attr("disabled",true);
      }

      // images pane ***************************** (we don't meed to do this if we've only had a bid)

      if (!in_auction) {
        if (auction_details[7] == "") { 
             // no images
             tabs_container = '<div class="wpa-tabs-content"><img src="http://lawtonphil.com/site-content/plugins/wp-auctions/style/default-300.png" alt="Image" /></div>';
             tabs = '<a href="#"><img src="http://lawtonphil.com/site-content/plugins/wp-auctions/style/default-50.png" alt="Image" /></a>';
        } else {	    
             thumbs = auction_details[18].split('^');
        
             tabs_container = '<div class="wpa-tabs-content"><img src="' + auction_details[7] + '" alt="Image" /></div>';
             tabs = '<a href="#"><img src="' + thumbs[thumbs.length - 1] + '" alt="Image" /></a>';
        
             // additional images
             for(var i=0;i<3;i++) {
               if (auction_details[12+i] != '') { 

                  tabs_container = tabs_container + '<div class="wpa-tabs-content"><img src="' + auction_details[12+i] + '" alt="Image" /></div>';
                  tabs = tabs + '<a href="#"><img src="' + thumbs[i+1] + '" alt="Image" /></a>';

               }
            }	    
        }
        jQuery("#wpa-tabs-container").html( tabs_container );
        jQuery("#wpa-tabs").html( tabs );	
	    
        resetTabs();
      }
     }
   });

     // get bids
     ajax_bids_request(auction_id);
	 
     // fire off call to update other auctions
     ajax_other_request(auction_id);

	 return false;
}

function ajax_bids_request(auction_id) {

   var currencysymbol = jQuery("input#currencysymbol").val();  
   var engine = jQuery("input#engine").val();  
   var customcontact = "Phone";
   
   if (ajax_bid_loading) return false;
   ajax_bids_loading ( true );

   // new jQuery AJAX routine
   jQuery.ajax ({
      cache: false,
      type: "POST",
      url: 'http://lawtonphil.com/site-content/plugins/wp-auctions/wp_auctions.php?querybids',
      data : {
         auction_ID : auction_id,
         engine : engine,
         _ajax_nonce: 'f251227d8b'
      },
      error: function(request,textStatus,errorThrown) {
	    alert((request.status!=406? ' WP_Auction Error '+request.status+' : '+request.statusText+'\n' : '')+request.responseText);
      },
   success: function(request, status) {

	    ajax_bids_loading(false);   

	    if (status!="success") alert (status);  //"return"

          current_winner = "None";
	    
	    // update bids on screen
        if (request == '') {
           var bid_output = 'No bids found';
        } else {
           bids_details = request.split('|');

           var bid_output = '<ol>';
           var lines = (bids_details.length/5)-1;
	       for(var i=0;i<lines;i++) {
	       
	            if ( current_winner == "None" ) current_winner = bids_details[i*5+1];
	       
              bid_output = bid_output + '<li>';
              if (bids_details[i*5+2]=="" || customcontact != "") {
                 bid_output = bid_output + bids_details[i*5+1];
              } else {
                 bid_output = bid_output + '<a href="' + bids_details[i*5+2] + '" target="_blank">' + bids_details[i*5+1] + '</a>';
              }
              bid_output = bid_output + ' bid ' + currencysymbol + bids_details[i*5+4] + ' on ' + bids_details[i*5+3];
              if (bids_details[i*5+5] == "auto") {
                 bid_output = bid_output + ' [auto]';
              }
              bid_output = bid_output + '</li>';
           }
	       bid_output = bid_output + '</ol>';
        }   

        jQuery('#wpa-currentbids').html(bid_output); 
        jQuery('#wpa-currentbidwinner').html(current_winner); 

	 }})
	 
	 return false;
}


function ajax_other_request(auction_id) {

   if (ajax_other_loading) return false;
   ajax_others_loading ( true );

   var currencysymbol = jQuery("input#currencysymbol").val();
   
   // new jQuery AJAX routine
   jQuery.ajax ({
      cache: false,
      type: "POST",
      url: 'http://lawtonphil.com/site-content/plugins/wp-auctions/wp_auctions.php?queryother',
      data : {
         auction_ID : auction_id,
         _ajax_nonce: 'f251227d8b'
      },
      error: function(request,textStatus,errorThrown) {
   	    alert((request.status!=406? ' WP_Auction Error '+request.status+' : '+request.statusText+'\n' : '')+request.responseText);
      },
   success: function(request, status) {

	    ajax_others_loading(false);   

	    if (status!="success") alert (status);  //"return"
	    
	    // update others on screen - returns multiples of 3, max 12

      if (request == "") {
         jQuery('#wpa-otherauctions').html(''); 
      } else {
      
        other_details = request.split('|');
     
          odetdiv = '';
          for(var i=0; i < 4;i++) {
             if (other_details[i*7+3] != undefined) {
                $image = other_details[i*7+3];
                if ($image == '') {
                   $image = 'http://lawtonphil.comPLUGIN_EXTERNAL_PATH/style/default-30.png';
                }
                
                odetdiv = odetdiv + '<p class="clearfix">';
                odetdiv = odetdiv + '<a href="#" title="' + other_details[i*7+2] + '" onclick="document.getElementById(\'formauctionid\').value=' + other_details[i*7+1] + ';ajax_auction_request()">';
                odetdiv = odetdiv + '<img src="' + $image + '" alt="' + other_details[i*7+2] + '" />';
                odetdiv = odetdiv + other_details[i*7+2];
                if (other_details[i*7+6] > 0) {
                   odetdiv = odetdiv + '</a> <br />Current bid: '+currencysymbol+other_details[i*7+6]+'</p>';
                } else {
                   odetdiv = odetdiv + '</a> <br />Buy It Now: '+currencysymbol+other_details[i*7+7]+'</p>';
                }
                
             } else {
                // Should be nothing here .. let's see how it goes ..
             }
          }
   
          jQuery('#wpa-otherauctions').html(odetdiv);
     }

	 }})
	 
	 return false;
}


function ajax_submit_bid(type) {
  
   // retreive form values
   var auction_id = jQuery("input#formauctionid").val(); 
   if ( type == 0 ) {   // standard bid
   
      var bidder_name = jQuery("input#wpa-popyourname").val();
      var bidder_email = jQuery("input#wpa-popyouremail").val();
      var bidder_url = jQuery("input#wpa-popcustomfield").val();
      var max_bid = jQuery("input#wpa-popbid").val();
      var BIN_amount = "";
   } else {            // BIN

      var bidder_name = jQuery("input#wpa-popyournamebin").val();
      var bidder_email = jQuery("input#wpa-popyouremailbin").val();
      var bidder_url = jQuery("input#wpa-popcustomfieldbin").val();
      var max_bid = jQuery("input#wpa-popbin").val();  
      var BIN_amount = jQuery("input#wpa-popbin").val();   
   }

   // new jQuery AJAX routine
   jQuery.ajax ({
      cache: false,
      type: "POST",
      url: 'http://lawtonphil.com/site-content/plugins/wp-auctions/wp_auctions.php?postauction',
      data : {
         auction_id   : auction_id,
         bidder_name  : bidder_name,
         bidder_email : bidder_email,
         bidder_url   : bidder_url,
         max_bid      : max_bid,
         BIN_amount   : BIN_amount,
         _ajax_nonce: 'f251227d8b'
      },
      error: function(request,textStatus,errorThrown) {
   	    alert((request.status!=406? ' WP_Auction Error '+request.status+' : '+request.statusText+'\n' : '')+request.responseText);
      },
   success: function(request, status) {

	    if (status!="success") alert (status);  //"return"

      // trim it (17/5/20 - no idea why i'm doing this
      request = jQuery.trim(request);
   
      // give user their response
      alert ( request );

       // fire off call to update auction details
       ajax_auction_request(auction_id);

	 }})
	 
	 return false;
}

function wpa_register_watcher( source ) {

  var auction_id = jQuery("input#wpa-" + source + "id").val();
  var watch_email = jQuery("input#wpa-" + source + "email").val();

   // new jQuery AJAX routine
   jQuery.ajax ({
      cache: false,
      type: "POST",
      url: 'http://lawtonphil.com/site-content/plugins/wp-auctions/wp_auctions.php?postwatch',
      data : {
         auction_id   : auction_id,
         watch_email  : watch_email,
         _ajax_nonce: 'f251227d8b'
      },
      error: function(request,textStatus,errorThrown) {
   	    alert((request.status!=406? ' WP_Auction Error '+request.status+' : '+request.statusText+'\n' : '')+request.responseText);
      },
   success: function(request, status) {

	    if (status!="success") alert (status);  //"return"

      // give user their response
      alert ( request );

	 }})
	 
	 return false;

}

function get_rss() {
   window.location = "http://lawtonphil.com/site-content/plugins/wp-auctions/wp_auctions.php?rss";
}

function resetTabs() {
   jQuery(".wpa-tabs").tabs("> .wpa-tabs-container > .wpa-tabs-content", { effect: "fade", fadeOutSpeed: "slow", rotate: true });
}

jQuery(function() {
   jQuery("#wpa-other div.wpa-other-item");
   jQuery("h4").toggle(function(){ jQuery(this).addClass("wpa-current"); }, function () { jQuery(this).removeClass("wpa-current"); });
   jQuery("h4").click(function(){ jQuery(this).next("#wpa-other div.wpa-other-item").slideToggle("medium"); });
});
    
// Form tooltip
jQuery("#wpa-form :input").tooltip({ position: "top center", offset: [ -10, 0], effect: "fade", opacity: 0.9, tipClass: 'wpa-tooltip' });
    
// Image Tabs
jQuery(function() { jQuery(".wpa-tabs").tabs("> .wpa-tabs-container > .wpa-tabs-content", { effect: "fade", fadeOutSpeed: "slow", rotate: true }); });
  
