var price_array = new Array();
var processed_hash = new Array(); 
var num_of_pages = parseInt(1);
var page_number = parseInt(1);
//var loop_count = parseInt(1);
var save_all_pricing_data = '';
var error_return_count = parseInt(0);
var cached_data = 0;
var weekday_array = new Array();
var month_array = new Array();
var opt = 'first_call';
var debug_array = new Array();
var multi_site = '0';
var ebay_site = '';
//initXML();

var timeleft_raw = new Array('P1D','P','D','T1H','H','T1M',' 1M','M','T1S',' 1S','S','T')
var timeleft_convert = new Array('1 d ','',' d ','1 h ',' h ','1 m ','1 m ',' m ','1 s ','1 s ',' s ','')
//var timeleft_convert = new Array('1 day ','',' days ','1 hr ',' hrs ','1 min ','1 min ',' mins ','1 sec ','1 sec ',' secs ','')

weekday_array['0']= 'Sun';
weekday_array['1']= 'Mon';
weekday_array['2']= 'Tue';
weekday_array['3']= 'Wed';
weekday_array['4']= 'Thu';
weekday_array['5']= 'Fri';
weekday_array['6']= 'Sat';

hostname = window.location.host;

function doit(temp_page){
   page = temp_page
   userid = document.forms['sellerform'].userid.value;
   stripuserid = document.forms['sellerform'].stripuserid.value;
//alert('here '+stripuserid+ ' '+userid)
//------------------------------------------------------------------------------
// Turn around and go get the list of eBay sites this member has items listed on 
//------------------------------------------------------------------------------
   geturl= 'http://'+ hostname +'/cgi-bin/get_member_sites_2.pl?id=' + encodeURIComponent(stripuserid) ;
   getSeverFile(geturl,'got_member_sites()');
//------------------------------------------------------------------------------

}
function got_member_sites(){
   site_array = new Array();
   site_array = eval('(' + get_server_reply + ')');  // do an eval on JSON structure returned from getting member sites
   //alert(site_array)
   doit_real(page)
   //for (var i in myObject.ItemSet.items) {
}


function initXML(){
 xmlhttp=false;
 //-------------------------------------------------------------------------------
 // NOTE - THE LINES BELOW ARE NOT COMMENTS
 //------------------------------------------------------------------------------- 
 /*@cc_on @*/
 /*@if (@_jscript_version >= 5)
 // JScript gives us Conditional compilation, we can cope with old IE versions.
 // and security blocked creation of the objects.
  try {
   xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
   try {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (E) {
    xmlhttp = false;
   }
  }
 @end @*/
 if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
   xmlhttp = new XMLHttpRequest();
 }


 //alert('xmlhttp init done')

}
//--------------------------------------------------------------------------
// Issue REST request
//--------------------------------------------------------------------------
function getSeverFile(url,where_to_go){
    
    //alert('issuing getserverfile  '+url)

 initXML();

 xmlhttp.open("GET", url, true);
 get_server_reply = 'primed';
 xmlhttp.setRequestHeader("Cache-Control", "no-cache");  // Since IE will cache the last response
 xmlhttp.setRequestHeader("Cache-Control", "must-revalidate"); 
 xmlhttp.onreadystatechange=function() {
     if (xmlhttp.readyState==4) {
        if (xmlhttp.status == 200) {
           get_server_reply = xmlhttp.responseText;
           //alert('server reply is '+ get_server_reply)
           if (where_to_go != 'nowhere') {
               junk = eval(where_to_go);                    //bounce back to original caller when done
           }
        } 
        else {
            //alert("There was a problem processing your request, please try again :\n" + xmlhttp.statusText);
        }
     }
 }
 xmlhttp.send(null)   // This forces a callback to the function above once a response is received
}
//--------------------------------------------------------------------------
function save_new_cache_data(data,saveoption,stripid,userid){

 //alert('saving cache data '+ data+' '+saveoption);
 //return ; // DON'T SAVE ANY DATA TILL WE"RE DONE DEBUGGING THE MULTI EBAY SITE FIX 10/31/07 

 store_server_reply =  '';

 xmlhttp.open("POST", 'http://'+ hostname +'/cgi-bin/SaveRESTPrices_2.pl', true);

 xmlhttp.setRequestHeader("Cache-Control", "no-cache");  // Since IE will cache the last response
 xmlhttp.setRequestHeader("Cache-Control", "must-revalidate"); 
 xmlhttp.onreadystatechange=function() {
     if (xmlhttp.readyState==4) {
        store_server_reply = xmlhttp.responseText;
       // junk = eval(where_to_go);               //bounce back to original caller when done
     }
     else{store_server_reply = 'ERROR';}
 }
 xmlhttp.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded; charset=UTF-8');
 xmlhttp.send('data='+encodeURIComponent(data)+'&option='+encodeURIComponent(saveoption)+'&userid='+encodeURIComponent(userid)+'&stripuserid='+encodeURIComponent(stripid)); 
}

function doit_real(page){

   if (page == 0) {page = 1;}  //we no longer use the "Skip" parm on the rest call, we now use page numbers and the link in html galleries already passes 0   

   if (page == 1){                       // get the ebay site we need to pull from
       ebay_site = site_array.pop();
   }

  
  document.getElementById('prices_link').innerHTML = '<IMG border=0 alt="Collecting Current Prices" src="/backgrounds/progress2.gif" >';
  //initXML()

  geturl= 'http://'+ hostname +'/cgi-bin/echoREST_2.pl?id=' + encodeURIComponent(stripuserid) + '&userid='+ encodeURIComponent(userid) + '&page_number='+ encodeURIComponent(page)+'&option='+encodeURIComponent(opt)+'&site='+encodeURIComponent(ebay_site) ;
  
  //alert('page is '+page+' url is '+geturl)
  
  getSeverFile(geturl,'doit2()'); 
}

function doit2(){        
    //------------------------------------------------------------------------------------------------------------------------------------------
    //  Format of data returned from REST call after our XSLT file had been applied is as follows (pagination and error info also returned) -   
    //  This is JSON format so we just have to issue an eval against it below - 
    //
    // {"ItemSet": {"num_of_pages": "1", "errorClass": "","longmsg":"","items": [ 
    // {"I":{"n":"220017444160","d":"USD|9.99||1|2006-08-22T01:10:15.000Z|Days_7|Chinese|false|NotSpecified|"}},
    // {"I":{"n":"220017445569","d":"USD|1.61||3|2006-08-22T01:15:15.000Z|Days_7|Chinese|false|NotSpecified|"}}, ] }}
    //------------------------------------------------------------------------------------------------------------------------------------------
    
   //alert('in doit2 back from call ... reply from server is '+get_server_reply)

  if (get_server_reply.indexOf('ATAL ERROR') > -1) {    // server says to give up 
      alert('Current price information is not available. \n Please try again later. \n You can click an item image to view it\'s Current Price.');   
      document.getElementById('prices_link').innerHTML = ' ';
      return;
  }
    
  if (get_server_reply.indexOf('cached_data') > -1) { 
      //alert('We have cached data  '+ get_server_reply)
      var temp_array  = get_server_reply.split("cached_data");
      get_server_reply = temp_array[0];
      cached_data = 1
  }
  else {                           // not cached data so need to concatenate prices from all REST calls made
      //alert('no cached data in reply '+ get_server_reply)
      var prices_array = get_server_reply.split("[");
      save_prices_begining_json = prices_array[0]

      //var price_data_array = prices_array[1].split("]");
      //save_all_pricing_data =  save_all_pricing_data  +  price_data_array[0];


  }

  //alert(get_server_reply)


  var myObject = eval('(' + get_server_reply + ')');  // do an eval on JSON structure returned from either a REST call or cached data
  

  //error_longmsg = myObject.ItemSet.longmsg;
  //if (error_longmsg !='') {
  //    error_code = myObject.ItemSet.errorcode;
  //    //alert(error_return)
  //    opt =  'resterror'+'|'+error_code +'|'+error_longmsg;
      
  //var debug = '';  
  for (var i in myObject.ItemSet.items) {
        //alert('key is: ' + i + ', value is: ' + myObject.ItemSet[i].I.n + 'data is '+ myObject.ItemSet[i].I.d);
        
        var temp_array=myObject.ItemSet.items[i].I.d.split("|");
        
        itemnum  = myObject.ItemSet.items[i].I.n
        
        //---------------------------------------------------------------------------------------------
        // Test if we have this item number already ... this can happen with the multi ebay site calls  
        //---------------------------------------------------------------------------------------------
        //if (multi_site == '1' && processed_hash[itemnum]){
        if (processed_hash[itemnum]){
           //alert('duplicate item '+ itemnum)
           continue;    
        }

        processed_hash[itemnum] = '1';

        currency = temp_array[0];
        price    = temp_array[1];
        bin      = temp_array[2];
        bids     = temp_array[3];
        endtime  = temp_array[4];
        duration = temp_array[5];
        itemtype = temp_array[6];
        //loc      = temp_array[7];
        binenabled=temp_array[7];
        shiptype = temp_array[8];
        shipcost = temp_array[9];
        paymethods = temp_array[10];
        loc= temp_array[11];

        keeper = '{"I":{"n":"'+itemnum+'","d":"'+temp_array[0]+'|'+temp_array[1]+'|'+temp_array[2]+'|'+temp_array[3]+'|'+temp_array[4]+'|'+temp_array[5]+'|'+temp_array[6]+'|'+temp_array[7]+'|'+temp_array[8]+'|'+temp_array[9]+'|'+temp_array[10]+'|'+temp_array[11] + '"}},';

        save_all_pricing_data = save_all_pricing_data + keeper; 
        
       // debug_array.push('location is '+ loc + ' itemtype is '+itemtype+' binenabled is '+binenabled+ ' shipitype is '+shiptype + ' shipcost is '+ shipcost+ ' '+'paymethods is '+paymethods+'\n')
        
       //return
        
        shipping = '';
        bids = '<b>'+bids+'</b>';
        if (duration == '') {
            duration='n/a';
        }
        var p_array=price.split(".");
        if (p_array[1].length< 2){price =  price + '0';}
        if (bin !=''){
            var b_array=bin.split(".");
            if (b_array[1].length< 2){bin =  bin + '0';}
        }

        if (p_array[1].length > 2){
            temp = p_array[1].substring(0,2);
            price =  p_array[0]  + '.' +  temp ;
        }

        var price_symbol = currency + ' ';

        if (currency=='USD' ) {price_symbol = '$';}
        if (currency=='AUD' ) {price_symbol = 'AU $';}
        if (currency=='CAD' ) {price_symbol = 'C $';}

        var price = price_symbol + '<b>' + price + '</b>' ; 
        var bin = price_symbol + '<b>' + bin + '</b>'; 
        var shipcost = price_symbol + shipcost;
        pricing = 'Current Price - '+ price + '<BR>';
        if (itemtype == 'C') {
          if (binenabled == 't') {
              bin = '<img align="top" border="0" alt="Buy It Now" src="http://'+ hostname +'/bin_15x54.gif"/> - <b> '+ bin +'</b>';
              pricing = 'Current Price - '+ price + '<BR> '+ bin +'<BR>'; 
          }
          else{bin='';}
        }
        if (itemtype == 'SFP' ||  itemtype == 'FP') {
            pricing = '<img align="top" border="0" alt="Buy It Now" src="http://'+ hostname +'/bin_15x54.gif"/> - <b>'+ price +'</B><BR>';
        }
        if (shiptype == 'C'){shiptype = 'Calculated'}
        shipping = 'Shipping - '+shiptype +'<BR>';
        if (shiptype == 'F') {
            var s_array=shipcost.split(".");
            if (s_array[1].length< 2){shipcost =  shipcost + '0';}
            if (s_array[1].length > 2){
                temp = s_array[1].substring(0,2);
                shipcost =  s_array[0]  + '.' +  temp ;
            }
            shipping = 'Shipping - <b>' +shipcost+'</b><BR>';
           // alert(shipping)
           // return
        }

        if (paymethods) {
            payments_line = 'Payments - '+ paymethods +'<BR>'; 
        }
        else{payments_line='';}

        if (shiptype == 'NS') {shipping = 'Shipping - see listing<BR>';}
        if (shiptype == 'Free') {shipping = 'Shipping - <b><font color=red>Free</font></b><BR>';}
        
        if (duration.indexOf('P') == 0) {     // handle TimeLeft ISO 186 duration format 
           
           var f = timeleft_raw, r = timeleft_convert, s = duration;
           var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
            while (j = 0, i--) {
                if (s[i]) {
                    while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
                }
            };
            duration =  sa ? s : s[0];
            
            //alert(duration)
        }
        else{
            if (duration == '1')  {duration = '1 day';}
            if (duration == '3')  {duration = '3 days';}
            if (duration == '5')  {duration = '5 days';}
            if (duration == '7')  {duration = '7 days';}
            if (duration == '10') {duration = '10 days';}
            if (duration == '30') {duration = '30 days';}
            if (duration == '60') {duration = '60 days';}
            if (duration == '90') {duration = '90 days';}
            if (duration == '120'){duration = '120 days';}
            if (duration == 'G')  {duration = 'GTC';}
        //2006-08-15T01:15:06.000Z
        }
        
        
        
        var date_array = endtime.split("-"); 
        var day_array = date_array[2].split("T");
        var time_array =  day_array[1].split(":");
        var sec_array =  time_array[2].split(".");
        //alert(endtime)
        date_array[1] = date_array[1] - 1
        var GMT_date =  new Date(date_array[0], date_array[1], day_array[0], time_array[0], time_array[1], sec_array[0])
        var GMT_hrs = GMT_date.getHours( )
        GMT_hrs = GMT_hrs - 8 
        GMT_date.setHours(GMT_hrs)
        var new_yr  = GMT_date.getFullYear( )
        var new_mon = GMT_date.getMonth( )
        var new_day = GMT_date.getDate( )
        var new_hr  = GMT_date.getHours( )
        var new_min = GMT_date.getMinutes( )
        var new_sec = GMT_date.getSeconds( )
        var new_wkday = GMT_date.getDay( )
        new_mon = new_mon + 1
        new_yr =   new_yr.toString()
        new_yr = new_yr.substring(2);
        new_mon = new_mon.toString()
        new_day = new_day.toString()
        new_hr = new_hr.toString()
        new_min = new_min.toString()
        new_sec = new_sec.toString()
        if (new_mon.length < 2) { new_mon = "0" + new_mon}
        if (new_day.length < 2) { new_day = "0" + new_day}
        if (new_hr.length < 2)  { new_hr  = "0" + new_hr}
        if (new_min.length < 2) { new_min = "0" + new_min}
        if (new_sec.length < 2) { new_sec = "0" + new_sec}
          //alert (weekday_array[new_wkday] +' '+ new_mon+'/'+new_day+'/'+new_yr+' '+ new_hr+':'+ new_min+':'+ new_sec + ' PDT')
        final_date = weekday_array[new_wkday] +' '+ new_mon+'/'+new_day+'/'+new_yr+' '+ new_hr+':'+ new_min+':'+ new_sec + ' PST';
        
        block = '<div style="width:185px;height:87px;vertical-align:bottom;text-align:left;font-size:7pt;font-family:Verdana;border:1px solid black;padding:2px;background-color: lightyellow;"> '+pricing+'Bids - ' + bids + '<BR>'+shipping + payments_line + 'Duration - '+duration+'<BR>Ends-'+ final_date +'</div>';
        price_array[itemnum] = block;
     
      }
        
        //  debug='';
        //  cnt = parseInt(0)
        //  for (var h in price_array) {
        //      debug = debug + 'key is '+h + 'val is '+price_array[h] +'\n';
        //      cnt = parseInt(cnt + 1);
        //  }
        // alert(debug + ' ' + cnt)
     
     if (cached_data == 1) {

         //alert('using cached data')
          parse_gallery()
          return;
     }
     else{

        num_of_pages = parseInt(myObject.ItemSet.num_of_pages);
        page_number = parseInt(page_number + 1);
        var temppg = parseInt(num_of_pages + 1) 
    
        //alert('num_of_pages is '+num_of_pages + ' page_number is ' +page_number+ ' temppg is ' +temppg);
        
        if (page_number == temppg ) {

                //alert('site array len is '+ site_array.length)
                
                if(site_array.length > 0){
                   page_number = 1;             // reset page number
                   opt='';                      // shut off first call indication
                   call_doit_real(page_number);
                   return;
                }

                full_rest_data = save_prices_begining_json + ' [ ' + save_all_pricing_data +  '] }}';
                saveopt = 'save';
                 
                //alert('calling save cached data sub')

                save_new_cache_data(full_rest_data,saveopt,stripuserid,userid);            
                parse_gallery()
        }


        if (page_number != temppg){
           //  if(opt != 'multi_site'){
                 opt='';                    // shut off first call indication
           //  }
             if (page_number == 8) {      // just in case
                 return
             }
             call_doit_real(page_number);
        }

  }  // end else if cached_data != 1

}


function call_doit_real(pg){
    doit_real(pg);
    return;
}

function parse_gallery(){
    
    //alert(debug_array)
    //return

    gal_rows = new Array();
    item_cell_array = new Array();
    temp_cell = new Array();
    gal_cells = new Array();
    rebuild_on_server = '';

    document.getElementById('prices_link').innerHTML = ' ';

    gal_table = document.getElementById("mag_cells");
    gal_rows = gal_table.getElementsByTagName("tr");
    //alert (gal_rows.length)
         for (var i=0;i<gal_rows.length;i++){
            found_an_empty_cell= 0;
            gal_cells = gal_rows[i].getElementsByTagName("td");
            if ( gal_cells.length == 4) {
                // if ( gal_cells[0].id.indexOf('INIPICSTART > 0')) {
                temp_cnt = parseInt(-1);
                for (var q=0 ;q < gal_cells.length; q++){
                   temp_cell[q] = '.';     //initialize temp cells array
                }
                for (var j=0;j<gal_cells.length;j++){   // should loop 4 times through each cell
                   cell_id = gal_cells[j].id;          // get the id (<td> id=xxx) for this cell
                   if (cell_id) {
                       cell_1_array = cell_id.split(" ");
                       cell_item = cell_1_array[0].split("MINIPICSTART") // parse itemnum out of cell id
                       if(price_array[cell_item[1]]){          //check if we have price info for this item
                           temp_cnt = temp_cnt + 1;
                           gal_cells[j].innerHTML = '<BR>'+ price_array[cell_item[1]] + '<BR>'+ gal_cells[j].innerHTML 
                           temp_cell[temp_cnt] = gal_cells[j].innerHTML 
                       }
                       else{
                           found_an_empty_cell= found_an_empty_cell +1;
                       }
                    }
                 }
                 if(found_an_empty_cell > 0){
                    if (found_an_empty_cell == 4) {
                        gal_rows[i].style.display = 'none'   // remove this row from view
                    }
                    else{
                       for (var f=0 ;f < gal_cells.length; f++){
                        gal_cells[f].innerHTML = temp_cell[f] ;     //replace with shifted cells
                       }
                    }
                 }
              }  // end of if gal_cells length > 2
          }     // end for all gal rows


 }



