// Popup front-end code

// This code needs to be refactored to consolidate all the similar routines

// 22nd Nov - ripped out countdown code

// 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 process_bin(BIN_price) {

   // make up replacement text and hidden field

   new_string = BIN_price + "(B.I.N. Price)";
   new_string = new_string + "<input name='BidAmount' type='hidden' id='BidAmount' value='" + BIN_price + "'/>"
   new_string = new_string + "<input name='BINAmount' type='hidden' id='BINAmount' value='" + BIN_price + "'/>"
   $('wp-bin-manip').innerHTML = new_string;
}

function swap_image(url) {

  $('wp-topimg-p').innerHTML = '<img src="' + url +'" alt="My Auction Image" width="190" height="190" />';

}


function ajax_auction_request() {

   // retreive form data
   auction_id = $F("formauctionid"); 
   currencysymbol = $F("currencysymbol");

   if (ajax_auction_loading) return false;
   
   ajax_auctions_loading ( true );
   new Ajax.Request('http://www.karmakandara.com/wp-content/plugins/wp-auctions/wp_auctions.php?queryauction', {
     method: 'post',
     asynchronous: true,
     parameters : "auction_ID="+auction_id,
	 onLoading: function(request) {
	    request['timeout_ID'] = window.setTimeout(function() {
	       switch (request.readyState) {
	          case 1: case 2: case 3:
	             request.abort();
	             alert('WP_Auction Error: Timeout\nThe server is taking too long to respond');
	             break;
	       }
	    }, 25000);
	 },
	 onFailure: function(request) {
	    alert((request.status!=406? ' WP_Auction Error '+request.status+' : '+request.statusText+'\n' : '')+request.responseText);
	 },
	 onComplete: function(request) {
	    ajax_auctions_loading(false);   
	    window.clearTimeout(request['timeout_ID']);
	    if (request.status!=200) alert (request.status);  //"return"
	    	    
	    // update auction on screen
	    auction_details = request.responseText.split('|');

	    // process BIN if there is one (note: only if auction isn't closed)
      extraBIN = "";
	    BIN_price = auction_details[11];
      if (BIN_price != 0 && auction_details[8] != 0) {
         extraBIN = "<a href='Javascript:process_bin(" + BIN_price + ");'>B.I.N. price: " + currencysymbol + BIN_price + "</a> - ";
      }

      // process extra images if there are any
      extraimages = '';
      thisimage = 1;
      for(var i=0;i<3;i++) {
         if (auction_details[12+i] != '') { 
            if (extraimages != '') {extraimages = extraimages + ", "; }
         
            swapurl = 'Javascript:swap_image("' + auction_details[12+i] + '")';
            extraimages = extraimages + "<a href='" + swapurl + "'>#" + thisimage++ + "</a>" 
         }
      }
      
      // if we DO have extra images, let's append the main image to the end of the list
      if (extraimages != '' && auction_details[7] != "") {
         swapurl = 'Javascript:swap_image("' + auction_details[7] + '")';
         extraimages = "More Images: " + extraimages + ", <a href='" + swapurl + "'>#" + thisimage + "</a>"       
      }

      // reset value field to form (in case previous BIN messed with this)
      $('wp-bin-manip').innerHTML = '<input name="BidAmount" type="text" class="formbid" id="BidAmount" value="" maxlength="8" align="right"/><input name="BINAmount" type="hidden" id="BINAmount" value="0"/>';



      // deal with Fixed Price BINs
      if (auction_details[6] == 0) {
         process_bin(BIN_price);
         $('wp_startb').innerHTML = "<strong>Starting Bid:</strong> B.I.N. price below";
         $('wp-extrainfo').innerHTML = "";
      } else {
         $('wp_startb').innerHTML = "<strong>Starting Bid:</strong> " + currencysymbol+auction_details[6];
         $('wp-extrainfo').innerHTML = "<font size='-2'>Bid " + currencysymbol + auction_details[15] + " or higher [<a href='http://www.wpauctions.com/faq' target='blank'>?</a>]</font>";
      }

      $('wp_desc').innerHTML = auction_details[2];
	    $('wp-tc-heading-p').innerHTML = auction_details[1];
	    $('wp_price').innerHTML = "Current Bid: " + currencysymbol + auction_details[3];
	    
	    if (auction_details[7] == "") { auction_details[7]='http://www.karmakandara.com/wp-content/plugins/wp-auctions//requisites/wp-popup-def.gif'   }
		  $('wp-topimg-p').innerHTML = '<img src="'+auction_details[7]+'" alt="My Auction Image" width="190" height="190" />';

        // Check if auction is still open
        if (auction_details[8] == 0) {
           // auction is closed
	       $('wp_endd').innerHTML = "Auction Ended";
           $("BidAmount").disabled = true;
           $('wp-bidnow-p').innerHTML = '';
           $('wp_winningb').innerHTML = '<strong>Winning Bid:</strong> ' + currencysymbol + auction_details[10] + ' by ' + auction_details[9];
        } else {
           // auction is open
	       $('wp_endd').innerHTML = "<strong>Ending Date:</strong> "+auction_details[5];
           $("BidAmount").disabled = false;
           $('wp-bidnow-p').innerHTML = '<a href="#" onclick="ajax_submit_bid();">Bid Now</a>';
           if (extraimages + extraBIN == '') {
              $('wp_winningb').innerHTML = '<strong>Winning Bid:</strong> Bid to win';
           } else {
              $('wp_winningb').innerHTML = extraBIN + "  " + extraimages;
           }
        }

        // trigger countdown code - TODO

	 }})
	 
     // fire off call to update 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) {

   currencysymbol = $F("currencysymbol");
   
   if (ajax_bid_loading) return false;
   
   ajax_bids_loading ( true );
   new Ajax.Request('http://www.karmakandara.com/wp-content/plugins/wp-auctions/wp_auctions.php?querybids', {
     method: 'post',
     asynchronous: true,
     parameters : "auction_ID="+auction_id,
	 onLoading: function(request) {
	    request['timeout_ID2'] = window.setTimeout(function() {
	       switch (request.readyState) {
	          case 1: case 2: case 3:
	             request.abort();
	             alert('WP_Auction Error: Timeout\nThe server is taking too long to respond');
	             break;
	       }
	    }, 25000);
	 },
	 onFailure: function(request) {
	    alert((request.status!=406? ' WP_Auction Error '+request.status+' : '+request.statusText+'\n' : '')+request.responseText);
	 },
	 onComplete: function(request) {
	    ajax_bids_loading(false);   
	    window.clearTimeout(request['timeout_ID2']);
	    if (request.status!=200) alert (request.status);  //"return"
	    
	    // update bids on screen
        if (request.responseText == '') {
           var bid_output = 'No bids found';
        } else {
           bids_details = request.responseText.split('|');

           var bid_output = '<ol class="wp-detailsbidders-p">';
           var lines = (bids_details.length/4)-1;
	       for(var i=0;i<lines;i++) {
              bid_output = bid_output + '<li><span class="wp-liststyle-p">';
              if (bids_details[i*4+2]=="") {
                 bid_output = bid_output + bids_details[i*4+1];
              } else {
                 bid_output = bid_output + '<a href="' + bids_details[i*4+2] + '" target="_blank">' + bids_details[i*4+1] + '</a>';
              }
              bid_output = bid_output + ' bid ' + currencysymbol + bids_details[i*4+4] + ' on ' + bids_details[i*4+3];
              bid_output = bid_output + '</span></li>';
           }
	       bid_output = bid_output + '</ol>';
        }   

        $('wp-detailsbidders-p').innerHTML = bid_output;

	 }})
	 
	 return false;
}


function ajax_other_request() {

   // retreive auction id
   var auction_id = $F("formauctionid");

   if (ajax_other_loading) return false;
   
   ajax_others_loading ( true );
   new Ajax.Request('http://www.karmakandara.com/wp-content/plugins/wp-auctions/wp_auctions.php?queryother&killcache=' + auction_id, {
     method: 'post',
     asynchronous: true,
     parameters : "auction_ID="+auction_id,
	 onLoading: function(request) {
	    request['timeout_ID3'] = window.setTimeout(function() {
	       switch (request.readyState) {
	          case 1: case 2: case 3:
	             request.abort();
	             alert('WP_Auction Error: Timeout\nThe server is taking too long to respond');
	             break;
	       }
	    }, 25000);
	 },
	 onFailure: function(request) {
	    alert((request.status!=406? ' WP_Auction Error '+request.status+' : '+request.statusText+'\n' : '')+request.responseText);
	 },
	 onComplete: function(request) {
	    ajax_others_loading(false);   
	    window.clearTimeout(request['timeout_ID3']);
	    if (request.status!=200) alert (request.status);  //"return"
	    
	    // update others on screen - returns multiples of 3, max 12

	    other_details = request.responseText.split('|');
	    
        odetdiv = '';
        for(var i=0;i<4;i++) {
           if (other_details[i*3+3] != undefined) {
              if (other_details[i*3+3] == '') {
                 odetdiv = odetdiv + '<a href="#" title="' + other_details[i*3+2] + '">';  
                 odetdiv = odetdiv + '<img src="http://www.karmakandara.com/wp-content/plugins/wp-auctions//requisites/wp-thumb-def.gif" border="0" alt="' + other_details[i*3+2] + '" width="50" height="50" onclick="document.getElementById(\'formauctionid\').value=' + other_details[i*3+1] + ';ajax_auction_request()"/>'; 
                 odetdiv = odetdiv + '</a>';  
              }
              else {
                 odetdiv = odetdiv + '<a href="#" title="' + other_details[i*3+2] + '">';  
                 odetdiv = odetdiv + '<img src="' + other_details[i*3+3] + '" border="0" alt="' + other_details[i*3+2] + '" width="50" height="50" onclick="document.getElementById(\'formauctionid\').value=' + other_details[i*3+1] + ';ajax_auction_request()"/>';  
                 odetdiv = odetdiv + '</a>';  
              }
           } else {
              // Should be nothing here .. let's see how it goes ..
           }
        }
 
        $('wp-othercontainer-p').innerHTML = odetdiv;

	 }})
	 
	 return false;
}


function ajax_submit_bid() {
 
   // retreive form values
   var auction_id = $F("formauctionid")
   var bidder_name = $F("Name");
   var bidder_email = $F("Email");
   var bidder_url = $F("URL");
   var max_bid = $F("BidAmount");
   var BIN_amount = $F("BINAmount");

   new Ajax.Request('http://www.karmakandara.com/wp-content/plugins/wp-auctions/wp_auctions.php?postauction', {
     method: 'post',
     asynchronous: true,
     parameters : "auction_id=" + auction_id + "&bidder_name="+bidder_name+"&bidder_email="+bidder_email+"&bidder_url="+bidder_url+"&max_bid="+max_bid+"&BIN_amount="+BIN_amount,
	 onLoading: function(request) {
	    request['timeout_ID'] = window.setTimeout(function() {
	       switch (request.readyState) {
	          case 1: case 2: case 3:
	             request.abort();
	             alert('WP_Auction Error: Timeout\nThe server is taking too long to respond');
	             break;
	       }
	    }, 25000);
	 },
	 onFailure: function(request) {
	    alert((request.status!=406? ' WP_Auction Error '+request.status+' : '+request.statusText+'\n' : '')+request.responseText);
	 },
	 onComplete: function(request) {  
	    window.clearTimeout(request['timeout_ID']);
	    if (request.status!=200) alert (request.status);  //"return"

		alert (request.responseText);

        // fire off call to update bids
        ajax_auction_request(auction_id);
	 }})
	 
	 return false;
}

function get_rss() {
   window.location = "http://www.karmakandara.com/wp-content/plugins/wp-auctions/wp_auctions.php?rss";
}

