var isSignedIn = false; 
var stepCnt = 0;
var step = $w('category description price_and_ship select_ebay_user');
var ORIG_DESC=" Add Custom Details about your Listing You can use Color too ! ";  
var userurl = null;

function init_sell() {

    var params = {"width":800,"skin":"sell","type":3};
    if($('iboxebaytarget')) {
        unhideIbox('ebaytarget');
        stepCnt++;
        return false;
    } 
    if(!createIbox($('ebaytarget'), params['skin'],'ebaytarget')){
    
        unhideIbox('ebaytarget');
    }
    else { 
      
              showIbox('<img src="<?php echo $this->baseUrl;?>/public/images/widget/indicator.gif" style="margin-left: 325px; padding: 30px 10px 10px 10px;">', 'ibox_footer', params,'ebaytarget');
              showBG('ebaytarget');
              window.onScroll = maintPos('ebaytarget');
              window.onResize = maintPos('ebaytarget');
              window.scrollTo(0,0); 
        new Ajax.Request('/sell',{ 
            method: 'get',
            parameters: {
            'previousstep': null,
            'step': step[stepCnt],
            'product': selectedItemUrl,
            'category': categoryId,
            'nextstep': step[stepCnt+1]},
            onSuccess: function(transport) {
              //var x = transport.responseText.evalScripts();
              showIbox(transport.responseText, 'ibox_footer', params,'ebaytarget');
              showBG('ebaytarget');
              window.onScroll = maintPos('ebaytarget');
              window.onResize = maintPos('ebaytarget');
              window.scrollTo(0,0); 
              initIboxEvents();
              } } ); 
  
    }
  stepCnt++;
}
function refreshSellers() { 
    var progress = "check_seller";
    var myRand = parseInt(Math.random()*99999999) ;
    var sendUrl = "/preview/step-publish_progress/msg-" + progress;
        sendUrl += "/refreshebayuser-1" ;
    new Ajax.Request(sendUrl, {
            method: 'get',
            onComplete: function(transport) {
              $('sellselect_ebay_user').innerHTML = transport.responseText;
              showBG('ebaytarget');
              window.onScroll = maintPos('ebaytarget');
              window.onResize = maintPos('ebaytarget');
              window.scrollTo(0,0); 
              }
        });
  $('ibox_close_aebaytarget').style.visibility="visible";
}
initIboxEvents = function () {
    var f =  $('list_preview_form');
    f.title.value = itemTitle;
    f.stock_image_url_small.value = imageMedium;
    f.category_id.value = categoryId;
    //f.original_cat_id.value = categoryId;
    f.stock_image_url.value = imageMedium;
    f.image_exists_0.value = (imageMedium) ? 1 : 0;
    f.image_local_0.value = (imageMedium) ? 'Stock Image' : null;
    f.has_image.value = (imageMedium) ? 1 : null;
    $('image_0').src = (imageMedium)? imageMedium : '/public/images/img-none-1.gif';
    $('image_1').src = '/public/images/img-none-1.gif';
    $('image_2').src = '/public/images/img-none-1.gif';
    $('image_3').src = '/public/images/img-none-1.gif';
    f.ztail_product_id.value = selectedItemId;
    f.url.value = selectedItemUrl;
    Event.observe('start_price','blur', function(event) {
            checkStartPrice(Event.element(event), Event.element(event).id) ;
            });
    Event.observe('reserve_price','blur', function(event) {
            checkReserve(Event.element(event), Event.element(event).id) ;
            });
    Event.observe('title','blur', function(event) {
             checkTitle(Event.element(event), Event.element(event).id) ;
            });
    Event.observe('video','blur', function(event) {
             checkVideo( Event.element(event), Event.element(event).id) ;
            });
    Event.observe('pkg_weight','blur', function(event) {
             checkPkgWeight( Event.element(event), Event.element(event).id) ;
            });
    Event.observe('catmsg','click', function(event) {
             toggleCatPicker( Event.element(event).id) ;
            });
    Event.observe('shipping_cost','blur', function(event) {
             checkShippingCost( Event.element(event), Event.element(event).id) ;
            });
    Event.observe('ibox_close_aebaytarget','click', function(event) {
             sellNext(null,1);
            });
    tinyMCE.init(
    {   mode : "exact",
        theme : "advanced",
        elements : "buyer_instructions",
        theme_advanced_buttons2 : "",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_buttons1 : "bold,italic,underline,separator,bullist,numlist,fontselect,fontsizeselect,separator,forecolor,link",
        extended_valid_elements :  "a[name|href|target|title],img[src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[width|size|noshade],font[face|size|color|style],span[align|style]",
        width: "100%"
  //      height: "100%"
}, 
    {   mode : "exact",
        theme : "advanced",
        elements : "description",
        theme_advanced_buttons2 : "",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_buttons1 : "bold,italic,underline,separator,bullist,numlist,fontselect,fontsizeselect,separator,forecolor,link",
        extended_valid_elements :  "a[name|href|target|title],img[src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[width|size|noshade],font[face|size|color|style],span[align|style]",
        width: "100%"
       // height: "100%"
    }); 
    if(tinyMCE.getInstanceById('description') == null) {
      tinyMCE.execCommand('mceAddControl', false, 'description');
    }
     //This code comment was associated with a scriptlet put in sell_price_and_ship.phtml for late rendering.
    /*if(tinyMCE.getInstanceById('buyer_instructions') == null) {
       tinyMCE.execCommand('mceAddControl', false, 'buyer_instructions');
    }*/
   
}
function toggleCatPicker(eventId) {

    $('catpicker').toggle();
    $('catradio').toggle();
    var radio = true;
    var picker = true;
    if( $('catpicker').style.display == '') {
        $(eventId).innerHTML = 'Go back to Ztail\'s suggested categories';
        radio = false;
        picker = true;

    }
    else {
        $(eventId).innerHTML = 'Use our Category Selection Tool';
        radio = true;
        picker = false;
    }
   
   $('catradio').childElements().each(function(n) {
        n.childElements().each(function(x) {
            if(x.type == 'hidden' || x.type == 'radio') {
              (radio) ? x.enable() : x.disable();
           }
           else {
              return;
          }
       });
   });

   $('picker_warning').hide();
  (picker) ? $('pickername').enable() : $('pickername').disable();
  (picker) ? $('pickervalue').enable() : $('pickervalue').disable();
}
function checkTitle(eventValue,eventId) {
    if ($F(eventId) == null || $F(eventId).length < 5) {
        $(eventId).next().innerHTML="Please specify good listing title!";
        $(eventId).next().show();
        $(eventId).focus();
        return false;
    }
    if ($F(eventId).length > 55) {
        $(eventId).next().innerHTML="Listing title cannot be more than 55 characters long";
        $(eventId).next().show();
        $(eventId).focus();
    }
   $(eventId).next().hide();
    return true;
}

function checkBuyerDesc() {
var desc = tinyMCE.get('buyer_instructions').getContent();

}
function checkDescription() {
 
 var desc = tinyMCE.get('description').getContent();
 var plainTextPersonalDesc = desc.stripTags().gsub(/(\s+|&nbsp;)/,'');
    if (plainTextPersonalDesc  == null || plainTextPersonalDesc.length < 5) {
        $('description').next('div').innerHTML="Please add a good description about this item!";
        $('description').next('div').show();
        return false;
    }
    if (ORIG_DESC.strip().gsub(/\s+/,'')  == plainTextPersonalDesc) {

        $('description').next('div').innerHTML="Please change the text above to your personal description about this item!";
        $('description').next('div').show();
        return false;
    }
        $('description').next('div').hide();
        return true;
}
function checkVideo(eventValue,eventId) {
    if($F(eventId) == null || $F(eventId) == '') {
        $(eventId).next().hide();
        return true;
    }
    if ( $F(eventId).indexOf("embed") < 0 ||
            $F(eventId).indexOf("application/x-shockwave-flash") < 0 ||
            $F(eventId).indexOf("object") < 0 ) {
        $(eventId).next().innerHTML="Please specify valid video embed code!";
        $(eventId).next().show();
        $(eventId).focus();
        return false;
    }
	
   $(eventId).next().hide();
   return true;

}
function validateCategory() {
    var catChecked = false;
    $R(0,20).each(function(n) {
       if($('cat' + n) && $('cat' + n).disabled == false) {
          if($F('cat' + n) != null) {
            catChecked = true;
         }
       } }) ;
    
    if(catChecked) {
        $('category_warning').hide();
        return true;
    }
    else {
        //check cat path
        if($('pickervalue').disabled == false && $F('pickervalue') > 1) {
           $('picker_warning').hide();
            return true;
        }
        else {
         $('picker_warning').show();
          return false;
        }
    }
    return false;
}

function setWizard(cnt) {
    $R(1,5).each(function(n) {
        if(n < cnt) {
            $('step_' + n).className = "Completed";
        }
        else if( n == cnt) {
            $('step_' + n).className = "Active";
        }
        else {
            $('step_' + n).className = "";
        }
   });
}

function sellNext(next,inc) {
  
    if(next == null) {
   
        if(inc == 0) {
           //cancel button
           hideIbox('ebaytarget');
           stepCnt = 0;
           return false;
        }
        if(inc == 1) {
          //ibox close
         $('sell' + step[stepCnt-1]).hide();
         //start at cat
         $('sell' + step[0]).show();
         //reset active/completed
          setWizard(1);
          hideIbox('ebaytarget');
          stepCnt = 0;
          return false;
        }

    }

    if(next == 'category') {
        setWizard(1);
    }

    if(next == 'description') {
       $('description_ifr').style.height = '145px';
        if(!validateCategory()) {
             
            return false;
        }
        else {
        ;
            setWizard(2);
        }

    }
    if(next == 'select_ebay_user') {
        if(!validatePriceandShipping()) {
        
            return false;
        }
        else {
            setWizard(4);
        }

    }
    if(next == 'price_and_ship') {
     /*   if(!validateDesc()) {
        alert('novalidation');
            return false;
        } */

       setWizard(3);
    }
    if($('sell' + next)) {
    
        $('sell' + step[stepCnt-1]).hide();
        $('sell' + next).show();
        (inc) ? stepCnt++ : stepCnt--;
        return false ;
    }
    return false;

}
        
//sellLoggedIn(refreshSellers, 'ebaytarget', doImageUpload);

function validateDesc() {

    if(!checkVideo( $('video'),'video') ) {
        return false;
    }
    if(!checkTitle($('title'),'title') ) {
        return false;
    }
    if(!checkDescription()) {
        return false;
    }
    
   return true;

}
function validatePriceandShipping() {
alert('hereee');
 if($F('shipping_calculation') == 'fix') {
    if(!checkShippingCost( $('shipping_cost'),'shipping_cost') ) {
        return false;
    }
 }
 if($F('shipping_calculation') == 'calculate') {
    if(!checkPkgWeight( $('pkg_weight'),'pkg_weight') ) {
        return false;
    }
 }
    if(!checkStartPrice( $('start_price'),'start_price') ) {
        return false;
    }
    var r = checkReserve( $('reserve_price'),'reserve_price') ;
    if(r == false) {
        return false ;
    } 
     return true;

}
function checkPkgWeight(eventValue,eventId) {
    var weight = checkInt($(eventId));
    if (weight == null ) {
        $(eventId).next().innerHTML = 'Invalid weight, it has to be a number!';
        $(eventId).next().show();
        return false;
    }
    if (weight == 0 ) {
        $(eventId).next().innerHTML = 'Invalid weight, it has to be at least 1 pound!';
        $(eventId).next().show();
        return false;
    }
    $(eventId).next().hide();
    return true;
}

function checkShippingCost(eventValue,eventId) {
alert('shippingcost');
    if (checkFloat($(eventId), 2) == null ) {
        $(eventId).next().innerHTML = 'Invalid shipping cost, it must be a valid number!';
        $(eventId).next().show();
        return false;
    }
    if ($F(eventId) == 0 ) {
        $(eventId).next().innerHTML = 'Invalid shipping cost, it has to be at least 1 dollar!';
        $(eventId).next().show();
        return false;
    }
    $(eventId).next().hide();
    return true;
  
}

function checkStartPrice(eventValue,eventId) {
    if (checkFloat($(eventId), 2) == null || $F(eventId).value == 0) {
        $(eventId + '_warning').innerHTML = 'invalid start price!';
        $(eventId + '_warning').show();
        return false;
    }
   
    checkReserve($F('reserve_price'),'reserve_price');
    
    updateEbayFees() ;
    $(eventId + '_warning').hide();
    return true;
}

function checkReserve(eventValue,eventId) {
        var start = $F('start_price');
        var reserve = $F(eventId);
    if (checkFloat($(eventId), 2) == null || $F(eventId).value == 0) {
        $(eventId + '_warning').innerHTML = 'Invalid reserve price';
        $(eventId + '_warning').show();
        return false;
    }
    
    if(Number(start) > Number(reserve) && Number(reserve) > 0) {
        $(eventId + '_warning').innerHTML = 'Start price cannot be higher than reserve price!';
        $(eventId + '_warning').show();
        return false;
    }

     updateEbayFees() ;

     $(eventId + '_warning').hide();
     return true;


}

function updateEbayFees() {
    var insertionFee =null;
    var reserveFee   =null;
    var durationFee  =null;
    if($F('start_price') > $F('reserve_price')) {
     insertionFee = getEbayInsertionFeeByStartPrice($F('start_price')).toFixed(2);
     $('insertion_fee').innerHTML = '$' + insertionFee;
    }
    else {
      insertionFee = getEbayInsertionFeeByStartPrice($F('reserve_price')).toFixed(2);
      $('insertion_fee').innerHTML = '$' + insertionFee;
    }
      reserveFee = getEbayInsertionFeeByReservePrice($F('reserve_price')).toFixed(2) ;
      $('reserve_calc').innerHTML = '$' + reserveFee;

      durationFee = getEbayInsertionFeeByListingDuration($F('duration')).toFixed(2) ;
      $('duration_calc').innerHTML = '$' + durationFee;

      $('total_fees').innerHTML = '$' + (Number(durationFee) + Number(reserveFee) + Number(insertionFee)).toFixed(2) ;



}
Event.observe(window, 'load', function() {
    if($('tabeBay3')) {
        Event.observe('tabeBay3', 'click', init_sell);
    }
    if($('sellItem')) {
        Event.observe('sellItem', 'click', init_sell);
    }
});

function checkShippingCostType(f) {
    // toggle which field-input to show based on shipping cost type

    if(f.value == 'fix') {
        $('shipping_input').show();
        $('weight_input').hide();

        $('shipping_cost').enable();
        $('pkg_weight').disable();
    } else if (f.value == 'calculate') {
        $('shipping_input').hide();
        $('weight_input').show();

        $('shipping_cost').disable();
        $('pkg_weight').enable();
    }
    return true;
}

function checkFloat(input, decimal) {
    if (typeof input == 'undefined' || input == null) {
        return null;
    }
    if (input.value.replace(/\s/g, '') == '') {
        input.value = 0;
    }
    if (isNaN(input.value) == true) {
        return null;
    }

    if (typeof decimal == 'undefined' || decimal == null) {
        decimal = 2;
    } else if (decimal > 4) {
        /* 4 decimal max */
        decimal = 4;
    }
    input.value = parseFloat(input.value).toFixed(decimal);
    return input.value;
}

function checkInt(input) {
    if (typeof input == 'undefined' || input == null) {
        return null;
    }
    if (input.value.replace(/\s/g, '') == '') {
        input.value = 0;
    }

    if (isNaN(input.value) == true) {
        return null;
    }

    input.value = parseInt(input.value);
    return input.value;
}


function getListingForm() {
    var f = null;
    for (var i=0; i < document.forms.length; i++) {
        if (document.forms[i].name == 'item_config_form') {
            return document.forms[i];
        } else if (document.forms[i].name == 'list_preview_form') {
            return document.forms[i];
        }
    }
    return null;
}


function getEbayInsertionFeeByStartPrice(price) {
    if (price==null || price == 0) {
        return 0;
    } else if (price < 1) {
        return 0.15;
    } else if (price < 10) {
        return  0.35;
    } else if (price < 25) {
        return  0.55;
    } else if (price < 50) {
        return  1.00;
    } else if (price < 200) {
        return  2.00;
    } else if (price < 500) {
        return  3.00;
    } else {
        return  4.00;
    }
}

function getEbayInsertionFeeByReservePrice(price) {
    if (price==null || price == 0) {
        return 0;
    } else if (price < 200) {
        return  2.00;
    } else {
        return  (0.01 * price > 50 ? 50 : 0.01 * price);
    }
}

function getEbayInsertionFeeByListingDuration(duration) {
    if (duration ==null) {
        return 0;
    } else if (duration == 10) {
        return 0.40;
    } else {
        return 0;
    }
}
function checkSeller(addUser) {
    var progress = "check_seller";
    var myRand = parseInt(Math.random()*99999999) ;
    var sendUrl = "/adduser/step-publish_progress/msg-" + progress;
    if (typeof addUser != 'undefined' && addUser == true) {
        sendUrl += "/addebayuser-1";
    }
    new Ajax.Request(sendUrl, {
            method: 'get',
            onComplete: function(transport) {
              $('sellselect_ebay_user').innerHTML = transport.responseText;
              }
        });

}

// user clicked "Submit" from checkSeller form (interstitial).
// the form is confirm_list
// and the forms is still open
function confirmPublishEbay(partnerId) {

     ///*hardcoded  */ ///////////////////////     
    f = getListingForm();  
    
    for (var j=0; j<f.elements.length; j++) {
    
    
            if (f.elements[j].name == 'image_local_1')
                f.elements[j].value="";
            if (f.elements[j].name == 'image_local_2')
                f.elements[j].value="";
            if (f.elements[j].name == 'image_local_3')
                f.elements[j].value="";
            if (f.elements[j].name == 'image_local_4')
                f.elements[j].value="";                  
    } 
    ///////////////////////////////////////
    var f = $('confirm_list');
    if (f == null) return false;

    var puid = 0;
    for (var i=0; i<f.elements.length; i++) {
        if (f.elements[i].name == 'puid' && f.elements[i].type == 'hidden') {
            puid = f.elements[i].value;
            break;
        } else if (f.elements[i].name == 'puid' && f.elements[i].checked) {
            puid = f.elements[i].value;
            break;
        }
    }
    if (puid == 0) {
        $('user_confirm').innerHTML= 'Please select a user';
        $('user_confirm').show();
        return false;
    }
    else {
        $('user_confirm').hide();
    }

    /* look for confirm checkbox */
    var isConfirmed = false;
    for (var i=0; i<f.elements.length; i++) {
        if (f.elements[i].name == 'confirm' && f.elements[i].checked ) {
        $('checkbox_confirm').hide();
            isConfirmed = true;
        } 
    }
    var rsvpConfirm = false;
    for (var i=0; i<f.elements.length; i++) {
        if (f.elements[i].name == 'confirmrsvp' && f.elements[i].checked ) {
        $('checkbox_confirm').hide();
            rsvpConfirm = true;
        } 
    }
    
    if (isConfirmed == false || rsvpConfirm == false) {
        $('checkbox_confirm').innerHTML= 'Please check both confirmation boxes to indicate you have read the terms';
        $('checkbox_confirm').show();
        return false;
    }

    /* now find the other values asscociated with the selected partner user id */
    var isAuth = 0, puName = '', chksum = '';
    for (var i=0; i<f.elements.length; i++) {
        if (f.elements[i].name == 'isauth_' + puid) {
            isAuth = f.elements[i].value;
        } else if (f.elements[i].name == 'puname_' + puid) {
            puName = f.elements[i].value;
        } else if (f.elements[i].name == 'chksum_' + puid) {
            chksum = f.elements[i].value;
        }
    }

    if (isAuth == 1) {
        //listItemPrepare('confirm', puid, chksum, null, puName);
        showListingProgress(puid, chksum, 'ebay');
    } else {
        window.open("/auth-seller/page-auth_request/partner_id-" + partnerId + "/partner_user_name-" + puName, "_blank", "width=750,height=600,resizable=yes,menubar=no,location=no,scrollbars=yes");
    }
}


/*this is called by clicking "OK" from 
 *confirmation inerstitial.
 */
function showListingProgress(partnerUserId, chksum, listingDestination) {
    if (typeof listingDestination == 'undefined' || listingDestination == null) {
        listingDestination = "ebay";
    }
    $('sellselect_ebay_user').innerHTML='<img src="/public/images/widget/indicator.gif" style="margin-left: 315px; padding: 30px 10px 10px 10px;">';
    listItem(null, partnerUserId, chksum);
}


/**
 * Does the real listing
 */
function listItem(f, partnerUserId, chksum,preview) {
    var formInputs = "step=publish_all&";
    if (f==null) {
        f = getListingForm();
    }

    var sendUrl = "/preview/step-publish/puid-" + partnerUserId + "/chksum-" + chksum;
    new Ajax.Request(sendUrl,{
method: 'POST',
parameters: f.serialize(),
onSuccess: function(transport) { 
             if(partnerUserId == 0) {
             
                 $('sellselect_ebay_user').innerHTML=transport.responseText;
                 $('ibox_close_aebaytarget').style.visibility="hidden";
             }
             else {
             
               //alert(transport.responseText);
                $('sellselect_ebay_user').replace(transport.responseText);
                   
                /*    transport.responseText.evalScripts();
                     if(publishStatus() == 1) {
                    success
                    var pItem = publishedId();
                    var pCat  = publishedCatId();
                    $('sellselect_ebay_user').replace(transport.responseText);
                    if (!Prototype.Browser.IE) {
                       $Launchpad.ShowMenu({wid: "4813a48901a27140", targetElement: "clearspring2", menuHeight: "254", config:{color:"ff0000" , itemId: pItem, categoryID: pCat } });
                   }
                   setWizard(5);
                   }else {
                   alert('sellselectebay'); 
                    $('sellselect_ebay_user').replace(transport.responseText);
                   }  */
             }

              showBG('ebaytarget');
              window.onScroll = maintPos('ebaytarget');
              window.onResize = maintPos('ebaytarget');

                } 
    });
    return;
}



function remove_progress(msg, id) {
    try {
        unspinner(id);
    } catch (e) {}

    if (msg != null) {
        setAlertMsg("error", msg, undefined);
    }
}



/** 
 * Only seller authentication page (which is a child window) calls this */
function gotoListItemPage(authStatus, puid, chksum) {
    window.blur();
    //window.close();
    if (authStatus == "success") {
        window.opener.focus();
        window.opener.remove_progress(null, null);
        //window.opener.listItemPrepare('confirm', puid, chksum, window);
        window.opener.showListingProgress(puid, chksum, 'ebay');
    } else {
        window.opener.remove_progress('Authentication failed!');
    }
    var t=setTimeout("window.close()",5000);
}

function addEbayUserCheck(loggedIn) {
    aLoggedIn(addNewEbayUser.curry(loggedIn), 'ebaytarget', addEbayUserCheck);
}

function addNewEbayUser(loggedIn) {

    var f = $('ebay_auth_add_user');
    var newEbayUser = f.ebay_user_name.value;

    var msgDiv = $('ebay_user_name_msg'); 
    if (newEbayUser == null || newEbayUser.length < 2 || newEbayUser =='add your ebay id') {
        if (msgDiv == null) {
            alert("eBay user name is blank or too short!");
        }
        msgDiv.className= 'WarningBox';
        msgDiv.innerHTML = "eBay user name is blank or too short!";
        return;
    }
        msgDiv.className = 'WarningBoxProgress';
    msgDiv.innerHTML = 'Please wait...adding the new eBay user name!';


    // submit this
    var sendUrl = '/auth-seller/page-ebay_user_add/user_name-' + escape(newEbayUser);
    new Ajax.Request(sendUrl,{method: 'get',
            onComplete:  function(transport) { 
            if (transport.responseText == "Ok") {
                msgDiv.className = 'WarningBoxSuccess';
                msgDiv.innerHTML = "Successfully validated Ebay user: " + newEbayUser + "!";
                refreshSellers();
               return false;
            } else {
                msgDiv.className= 'WarningBox';
                msgDiv.innerHTML = transport.responseText;
                if(!loggedIn) {
                   msgDiv.insert(' Please click <a href="#" onclick="refreshSellers()">refresh</a> to you your list of sellers');
                }
                return false;
            }
        }
         //   msgDiv.innerHTML = "Error adding new eBay user!";
    });
}


function doImageUpload() {
    aLoggedIn(upload_image_form, 'ebaytarget', doImageUpload);
}

function upload_image_form() {
	//alert("ff");

    var f = getListingForm();

    if (f==null) return false;


    var uuid = f.image_uuid.value;
 /*   if (uuid == null || uuid == '') {
        return showLoginBox('ebaytarget',upload_image_form);
    }
   */ 

    var myRand = parseInt(Math.random()*99999999) ;
    //uuid = uuid.replace(/-/g, '_');
    var imageUploadBase = escape(f.image_upload_base.value);
    imageUploadBase = imageUploadBase.replace(/\//g, 'xSLASHx');
    var stockImageUrlSmall = escape(f.stock_image_url_small.value);
    stockImageUrlSmall = stockImageUrlSmall.replace(/\//g, 'xSLASHx');
    var sendUrl = "/list/imageupload-1/uuid-" + uuid + "/image_upload_base-" + imageUploadBase + "/stock_image_url-" + stockImageUrlSmall;
  //var sendUrl = '/list/';
    for (var j=0; j<5; j++) {
        for (var i=0; i<f.elements.length; i++) {
            if (f.elements[i].name == 'image_exists_' + j && f.elements[i].value!="") {
                sendUrl += '/image_exists_' + j + '-' + f.elements[i].value;
            } else if (f.elements[i].name == 'image_local_' + j && f.elements[i].value!="") {
                sendUrl += '/image_local_' + j + '-' + f.elements[i].value;
            }
        }
    }
   window.open(sendUrl, "_blank", "height=550,width=545", "resizable=0,menubar=no,scrollbars=no,location=0");
  // window.open(url, "_blank", "width=800,height=500,resizable=yes,menubar=no,scrollbars=yes,location=yes");
  // window.open(url, "ztail", "height=1600,width=1000","resizable=yes,menubar=yes,scrollbars=yes,toolbar=no,location=yes");
}

/**
 * This is from onload on Upload Images window.
 */
function updateImageFields(id) {
    if(window.opener) { 
    window.opener.$('image_upload_file').value =  window.opener.$F('image_upload_file').gsub('-1',id); 
    window.opener.$('image_upload_base').value =  window.opener.$F('image_upload_base').gsub('-1',id); 
    } 
    for (var i=0; i<5; i++) {
     }
}


/**
 * This is from "Upload Image" button
 * on Upload Images window.
 */
function clickUploadImage() {
    //onsubmit="return check_upload_image(this);"
    var submittedFormCnt = 0;
    for (var i=0; i<document.forms.length; i++) {
        // find <p> to see if there it's hidden or not.
        var f = document.forms[i];
        if (f.imagefile.value == null || f.imagefile.value.length == 0 || f.upload_status.value == 1) {
            continue;
        }

        // reset the iframe
        for (var j=0; j<f.childNodes.length; j++) {
            if (f.childNodes[j].nodeName != 'IFRAME') {
                continue;
            }
           if (navigator.appName.indexOf("Microsoft") != -1) {
                document.frames[i].document.body.innerHTML = '';
            } else {
                f.childNodes[j].contentDocument.body.innerHTML = '';
            }
            break;
        }

        // enable LOADING span.
        var p = null;
        for (var c=0; c<document.forms[i].childNodes.length; c++) {
            if (document.forms[i].childNodes[c].nodeName == "P" && document.forms[i].childNodes[c].getAttribute("name") == "inputs") {
                p = document.forms[i].childNodes[c];
                if (p.style.display == 'none') {
                    continue;
                }
            }
        }
        if (p==null) return;
        for (var j=0; j<p.childNodes.length; j++) {
            if (p.childNodes[j].nodeName == 'SPAN' && p.childNodes[j].getAttribute("name") == "uploading" ) {
                p.childNodes[j].style.display = "inline";
            } else if (p.childNodes[j].nodeName == 'SPAN' && p.childNodes[j].getAttribute("name") == "uploaded") {
                p.childNodes[j].style.display = "none";
            } else if (p.childNodes[j].nodeName == 'SPAN' && p.childNodes[j].getAttribute("name") == "failed") {
                p.childNodes[j].style.display = "none";
            }
        }

        f.upload_status.value = 2; /* 0=not-uploaded, 1=uploaded, 2=uploading, -1=failed */
        f.submit();
        submittedFormCnt += 1;
        setTimeout("checkUploadingImage(" + i + ");", 500);

    }
    if (submittedFormCnt == 0) {
        closeUploadImageWindow();
    }
}

function checkUploadingImage(i) {
    // find the iframe and inspect the content.
    var imageUploaded = false;
    var imageUploadSuccess = false;
    var f = document.forms[i];
    for (var j=0; j<f.childNodes.length; j++) {
        if (f.childNodes[j].nodeName != 'IFRAME') {
            continue;
        }
        try {
           if (navigator.appName.indexOf("Microsoft") != -1) {
                 /* get the right frame */
                 var IEIFrame = null;
                 for (var k=0; k<document.frames.length; k++) {
                    if (document.frames[k].name == "iframe_target_name_" + i) {
                        IEIFrame = document.frames[k];
                    }
                 }
                 if (IEIFrame != null && IEIFrame.document.body.innerHTML.length > 10) {
                    if (IEIFrame.document.body.innerHTML.indexOf('Woo hoo!') > 0) {
                        imageUploadSuccess = true;
                        f.upload_status.value = 1;
                    } else {
                        imageUploadSuccess = false;
                        f.upload_status.value = -1;
                    }
                    imageUploaded = true;
                 }
            } else {
                if (f.childNodes[j].contentDocument.body.innerHTML.length > 10) {
                    if (f.childNodes[j].contentDocument.body.innerHTML.indexOf('Woo hoo!') > 0) {
                        imageUploadSuccess = true;
                        f.upload_status.value = 1;
                    } else {
                        imageUploadSuccess = false;
                        f.upload_status.value = -1;
                    }
                    imageUploaded = true;
                }
            }
        } catch (e) {}
    }

    if (imageUploaded == false) {
        setTimeout("checkUploadingImage(" + i + ");", 500);
        return;
    }


    // get the P
    var p = null;
    for (var c=0; c<document.forms[i].childNodes.length; c++) {
        if (document.forms[i].childNodes[c].nodeName == "P" && document.forms[i].childNodes[c].getAttribute("name") == "inputs") {
            p = document.forms[i].childNodes[c];
            if (p.style.display == 'none') {
                continue;
            }
        }
    }
    if (p==null) return;


    for (var j=0; j<p.childNodes.length; j++) {
        if (p.childNodes[j].nodeName == 'SPAN' && p.childNodes[j].getAttribute("name") == "uploadinguploading" ) {
            p.childNodes[j].style.display = "none";
        } else if (p.childNodes[j].nodeName == 'SPAN' && p.childNodes[j].getAttribute("name") == "uploaded") {
            if (imageUploadSuccess) {
                p.childNodes[j].style.display = "inline";
            } else {
                p.childNodes[j].style.display = "none";
            }
        } else if (p.childNodes[j].nodeName == 'SPAN' && p.childNodes[j].getAttribute("name") == "failed") {
            if (!imageUploadSuccess) {
                p.childNodes[j].style.display = "inline";
            } else {
                p.childNodes[j].style.display = "none";
            }
        } else if (p.childNodes[j].nodeName == 'SPAN' && p.childNodes[j].getAttribute("name") == "remove_span") {
            p.childNodes[j].style.display = "inline";
        }
    }

    var img = $("image_preview_" + i);
    if (img != null) {
        var myRand = parseInt(Math.random()*99999999) ;
        if (imageUploadSuccess) {
            img.style.display = "inline";
            img.src = f.image_upload_url.value + "?xrand=" + myRand;
        } else {
            img.src = "";
            img.style.display = "none";
        }
    }

    // check if we can close the window.
    var imagesUploaded = true;
    for (var j=0; j<document.forms.length; j++) {
        if (document.forms[j].upload_status.value == 2 /*uploading*/ || document.forms[j].upload_status.value == -1 /*failed*/ ) {
            imagesUploaded = false;
        }
    }
    if (imagesUploaded) {
        setTimeout('closeUploadImageWindow();', 500);
    }

}


/**
 * User clicks "remove" on Image Upload window
 */
function removeImage(i) {
        // get the  image_name_span and hide it.
    var p = null;
    for (var c=0; c<document.forms[i].childNodes.length; c++) {
        if (document.forms[i].childNodes[c].nodeName == "P" && document.forms[i].childNodes[c].getAttribute("name") == "inputs") {
            p = document.forms[i].childNodes[c];
            // look for the SPAN that shows image file name and Remove link.
            for (var j=0; j<p.childNodes.length; j++) {
                if (p.childNodes[j].nodeName == 'SPAN' && p.childNodes[j].getAttribute('name') == 'image_name_span') {
                    p.childNodes[j].style.display = "none";
                } else if (p.childNodes[j].nodeName == 'SPAN' && p.childNodes[j].getAttribute('name') == 'remove_span') {
                    p.childNodes[j].style.display = "none";
                } else if (p.childNodes[j].nodeName == 'SPAN' && p.childNodes[j].getAttribute('name') == 'uploading') {
                    p.childNodes[j].style.display = "none";
                } else if (p.childNodes[j].nodeName == 'SPAN' && p.childNodes[j].getAttribute('name') == 'uploaded') {
                    p.childNodes[j].style.display = "none";
                } else if (p.childNodes[j].nodeName == 'SPAN' && p.childNodes[j].getAttribute('name') == 'failed') {
                    p.childNodes[j].style.display = "none";
                }
            }
        }
    }
    if (p==null) return;

    // mark upload_status = 0.
    for (var j=0; j<document.forms[i].elements.length; j++) {
        if (document.forms[i].elements[j].name == 'imagefile') {
            document.forms[i].elements[j].value = "";
            document.forms[i].elements[j].style.display = "inline";
        } else 
        if (document.forms[i].elements[j].name == 'upload_status') {
            document.forms[i].elements[j].value = "0";
        }
    }
    // remove the image from preview.
    var img = $("image_preview_" + i);
    if (img != null) {
        var myRand = parseInt(Math.random()*99999999) ;
        img.src = "/public/images/image-missing-80.gif?rand=" + myRand;
        img.style.display = "none";
    }
    //remove image name from preiview
     var img_span = $("image_preview_span" + i);       
        img_span.style.display = "none";
  
     
    
}

/**
 * This is when user press "Continue TO Listing" button
 * from Upload Images window.
 */
function closeUploadImageWindow() {
    // get window opener's document.
    var openerForm = null;

    try {
        openerForm = window.opener.getListingForm();
    } catch (e) {
        alert('error in getting window.opener.getListingForm();');
    }
    for (var i=1; openerForm != null && i<document.forms.length; i++) {
        // find the associated image field
        var openerFormImageExists = null;
        var openerFormImageLocal = null;
        for (var j=1; j<openerForm.elements.length; j++) {
            if (openerForm.elements[j].name == 'image_exists_' + (i)) {
                openerFormImageExists = openerForm.elements[j];
            } else if (openerForm.elements[j].name == 'image_local_' + (i)) {
                openerFormImageLocal = openerForm.elements[j];
            }
        }

        if (openerFormImageExists == null) continue;

        if (document.forms[i].upload_status.value == 1 && document.forms[i].imagefile.value.length > 0) { /* images were just uploaded by this window session */
           
            openerFormImageExists.value = 1;
            openerFormImageLocal.value = getFileName(document.forms[i].imagefile.value);
        } else if (document.forms[i].upload_status.value == 1 && document.forms[i].imagefilename.value.length > 0 ) { /* images were uploaded before this window opened (no INPUT-FILE shown) */
          
            openerFormImageExists.value = 1;
            openerFormImageLocal.value = getFileName(document.forms[i].imagefilename.value);
        } else { /* no images uploaded */
            openerFormImageExists.value = 0;
            openerFormImageLocal.value = "";
        }
    }
    try {
        window.opener.refresh_uploaded_image();
    } catch (e) {
      //  alert('error in getting window.opener.refresh_uploaded_image();');
       window.close();
    }
    window.close();
}


function getFileName(fullPath) {
    var dirSeparator = '/';
    if (navigator.appVersion.indexOf("Win") > -1) {
        dirSeparator = "\\";
    } else if (navigator.userAgent.toLowerCase().indexOf("mac os x") > -1) {
        dirSeparator = '/';
    } else if (navigator.appVersion.indexOf("Mac") > -1) {
        dirSeparator = ':';
    }
    var m = fullPath.split(dirSeparator);
    if (m==null) return null;

    return m[m.length-1];
}

function refresh_uploaded_image(imageSrc) {

/*alert('here??');*/
    f = getListingForm();
    imagenew = f.image_upload_base.value; 
    updatenew = f.image_upload_file.value;
    var updatesplit = updatenew.split('/'); 
    var  urlsplit = imagenew.split('/');
   
   
    if(urlsplit[5] == '')
    {
      /*alert('insideurlsplit');*/
    var sendUrl = '/edit/user';
    new Ajax.Request(sendUrl, {
            method: 'get',
            onComplete: function(transport) {
             
              urlsplit[5] = transport.responseText;
              updatesplit[5] = transport.responseText; 
               //alert(urlsplit.join("/")); 
               imagenew =  urlsplit.join("/");
               updatenew = updatesplit.join("/");
               f.image_upload_base.value = imagenew;
               f.image_upload_file.value = updatenew;
               refresh_uploaded_image_id(imagenew);
              }
        });
        
      //imagenew =  urlsplit.join("/");  
      return
    } 
     /*alert('out');   */
    imageSrc = f.image_upload_base.value;
    var firstAvailImage = true;
    var hasImages = false;
    var uploadedImages = false;
    // refresh image on STEP-2  (Manage Images)
    for (var i=0; i<5; i++) {
   
        var imageId = $("image_" + i);
    
        var imageExists = null;
        var imageLocal = null;
        for (var j=0; j<f.elements.length; j++) {
            if (f.elements[j].name == 'image_exists_' + (i)) {
              
                imageExists = f.elements[j];
            } else if (f.elements[j].name == 'image_local_' + (i)) {
           
                imageLocal = f.elements[j];
            }
        }
    
        if (imageExists == null) continue;
    
        if (imageExists.value == "1") {
         
            hasImages = true;
            /*if (imageLocal.value == 'Stock Image') { */
          if (i==0) {
            /*alert('here5stockC');*/   
                imageSrc = f.stock_image_url_small.value;
            } else {   
           
                uploadedImages = true;                
                imageSrc = f.image_upload_base.value + "_" + i + "_80.jpg";     
           }
        } else {
            imageSrc = "";
        }
    
        var myRand = parseInt(Math.random()*99999999) ;
            if(imageSrc == null || imageSrc.length < 5) {
                imageSrc='/public/images/img-none-1.gif';
            }

       /* imageSrc += "?rand=" + myRand;*/
        if (imageId != null ) {
        
            imageId.src = imageSrc;
            if (imageExists.value == "1") {
                imageId.style.display = "inline";
            } else {
                imageId.style.display = "";
            }
        } 
    
        if (firstAvailImage && imageExists.value == "1") {
         
            firstAvailImage = false;
            imageId = $("product_image_preview_id");
            if (imageId != null) {
                imageId.src = imageSrc;
            } 
        
            imageId = $("product_image_preview_sn_id");
            if (imageId != null) {
                imageId.src = imageSrc;
                setTimeout('openAnimation(3, true);', 200);
            } 
        }
    }

    if (hasImages) 
    {
    
        f.has_image.value = 1;
    } else {
      
        f.has_image.value = 0;
        imageId = $("product_image_preview_id");
        if (imageId != null) {
            imageId.src = "";
        } 
    }
    if (uploadedImages) {
        f.image_uploaded.value = 1;
    } else {
        f.image_uploaded.value = 0;
    }

  
    // update additional images in PREVIEW
    var addlImage = $("addl_images");
    if (addlImage != null) {
        // remove all elements first.
        while (addlImage.childNodes.length > 0) {
            addlImage.removeChild(addlImage.childNodes[0]);
        }
        var num = 0;
        for (var i=0 /*skip the first one*/; i<5; i++) { 
            try {
                if (f['image_exists_' + i].value == 1) {
                    if (num == 0) {
                        num += 1;
                        continue;
                    }
                    if (num == 1) {
                        var text = document.createElement("strong");
                        text.innerHTML = "Additional Product Images<br/>";
                        addlImage.appendChild(text);
                    }
                    var img = document.createElement("img");
                    var myRand = parseInt(Math.random()*99999999) ;
                    imgSrc = f.image_upload_base.value + "_" + i + ".jpg?rand=" + myRand;
                    img.setAttribute("src", imgSrc);
                    img.style.display = "inline";
                    img.style.marginRight = "10px";
                    addlImage.appendChild(img);

                    var br = document.createElement("br");
                    addlImage.appendChild(br);

                    num += 1;
                }
            } catch (e) {}
        }

    }

    f.title.focus();  
}

function close_image_upload() {
    try {
        unspinner('spinny-frame-small');
    } catch (e) {}
    f = getListingForm();
    if (f==null) {
        f.title.focus();
    }

}
function refresh_uploaded_image_id(imagenew) {
  
   
    f = getListingForm();
    imageSrc = f.image_upload_base.value;
    var firstAvailImage = true;
    var hasImages = false;
    var uploadedImages = false;
    // refresh image on STEP-2  (Manage Images)
    for (var i=0; i<5; i++) {
        var imageId = $("image_" + i);
    
        var imageExists = null;
        var imageLocal = null;
        for (var j=0; j<f.elements.length; j++) {
            if (f.elements[j].name == 'image_exists_' + (i)) {
                imageExists = f.elements[j];
            } else if (f.elements[j].name == 'image_local_' + (i)) {
                imageLocal = f.elements[j];
            }
        }
    
        if (imageExists == null) continue;
    
        if (imageExists.value == "1") {
            hasImages = true;
            if (imageLocal.value == 'Stock Image') {
                imageSrc = f.stock_image_url_small.value;
            } else {
                uploadedImages = true;
                imageSrc = imagenew + "_" + i + "_80.jpg";
            }
        } else {
            imageSrc = "";
        }
    
        var myRand = parseInt(Math.random()*99999999) ;
            if(imageSrc == null || imageSrc.length < 5) {
                imageSrc='/public/images/img-none-1.gif';
            }

        /*imageSrc += "?rand=" + myRand;*/
        if (imageId != null) {
            imageId.src = imageSrc;
            if (imageExists.value == "1") {
                imageId.style.display = "inline";
            } else {
                imageId.style.display = "";
            }
        } 
    
        if (firstAvailImage && imageExists.value == "1") {
            firstAvailImage = false;
            imageId = $("product_image_preview_id");
            if (imageId != null) {
                imageId.src = imageSrc;
            } 
        
            imageId = $("product_image_preview_sn_id");
            if (imageId != null) {
                imageId.src = imageSrc;
                setTimeout('openAnimation(3, true);', 200);
            } 
        }
    }

    if (hasImages) {
        f.has_image.value = 1;
    } else {
        f.has_image.value = 0;
        imageId = $("product_image_preview_id");
        if (imageId != null) {
            imageId.src = "";
        } 
    }
    if (uploadedImages) {
        f.image_uploaded.value = 1;
    } else {
        f.image_uploaded.value = 0;
    }

    // update additional images in PREVIEW
    var addlImage = $("addl_images");
    if (addlImage != null) {
        // remove all elements first.
        while (addlImage.childNodes.length > 0) {
            addlImage.removeChild(addlImage.childNodes[0]);
        }
        var num = 0;
        for (var i=0 /*skip the first one*/; i<5; i++) { 
            try {
                if (f['image_exists_' + i].value == 1) {
                    if (num == 0) {
                        num += 1;
                        continue;
                    }
                    if (num == 1) {
                        var text = document.createElement("strong");
                        text.innerHTML = "Additional Product Images<br/>";
                        addlImage.appendChild(text);
                    }
                    var img = document.createElement("img");
                    var myRand = parseInt(Math.random()*99999999) ;
                    imgSrc = f.image_upload_base.value + "_" + i + ".jpg?rand=" + myRand;
                    img.setAttribute("src", imgSrc);
                    img.style.display = "inline";
                    img.style.marginRight = "10px";
                    addlImage.appendChild(img);

                    var br = document.createElement("br");
                    addlImage.appendChild(br);

                    num += 1;
                }
            } catch (e) {}
        }

    }

    f.title.focus();
}
