
var photos_to_upload = 0;
var lastID = 0;
var photos_ok = 0;
var photos_upload_counter = 1;
var display_photos_uploader = true;
var myLightbox = null;
var changeCountry = 1;
var changeCategory = 1;
var showAccept = 1;
var Logger = 
{
  verbose: false,
  
  info: function(message)
  {
    Logger.say(message);
  },
  
  say: function(message)
  {
    if (Logger.verbose)
    {
      alert(message);
    }
  }
}

function validatePhotoExtension(sender)
{
  var url = sender.value;
  var extension = url.substring(url.lastIndexOf(".")).toLowerCase();
  var formAction;

  permitida = extension.trim().length == 0 || $w('.gif .jpg .jpeg .pjpeg .tiff .png').any(function(e) { return e == extension; });

  var current = sender.id.split('_')[1];

  if (permitida) {
    Element.hide('errorPhoto_' + current);
    Element.show(sender.form.getElementsByTagName('a')[0]);
  }
  else {
    Element.show('errorPhoto_'+current);
//    Form.reset(sender.form);
    Element.hide(sender.form.getElementsByTagName('a')[0]);
  }

  return permitida;
}

function addPhoto(max, field) {

  photos_length = $(field).getElementsByClassName('photo').length;

  $A($('field_photos').getElementsByTagName('form')).each(function(element) {
    Element.removeClassName(element, 'last');
  });

  if (lastID == 0) {
      if($('max_order'))
        lastID = $F('max_order');
      else
        lastID = photos_length;
  }

  if(photos_length < max) {
    lastID++;
    var photo_id = lastID;
       
    var insertHtml = "<form id='upload_form_photo_" + photo_id + "' name='upload_form_photo_" + photo_id + "' action='/backgroundProcess/uploadImagenes.php' method='post' enctype='multipart/form-data' target='upload_photos_frame' class=\"more last\">" +
          "<input type='hidden' name='numero' value='" + photo_id + "' />" +
          "<input type='hidden' name='f[" + photo_id + "][text]' value='' />" +
          "<input type='hidden' name='photoid[" + photo_id + "]' value='photo_" + photo_id + "' />"+
          "<input type='file' name='d[" + photo_id + "]' value='' id='photo_" + photo_id + "' class='photo' onchange='if (validatePhotoExtension(this)) { addPhoto(" + max + ", \"field_photos\"); }'/> "+
          "<a href=\"javascript:void(0)\" onclick=\"removePhoto(this);\">"+olxMsg['RemovePhoto'] +"</a> " +
          "<em class=\"optional\">("+olxMsg['optional'] +")</em>" +
          "<span style=\"display:none\" id=\"errorPhoto_" + photo_id + "\" >"+olxMsg['errorPhoto'] +"</span></form>";

    new Insertion.Bottom(field, insertHtml);
    
    if((photos_length+1) == max)
      Element.hide('add_photo');
  }
  checkTop();
}

function removePhoto(el, PhotoId) {

  if (lastID == 0) {
      if($('max_order'))
        lastID = $F('max_order');
      else
        lastID = $(field).getElementsByClassName('photo').length;
  }

  if(PhotoId > 0) {
    $(el).remove();
    Element.show('add_photo');
    var insertHtml = "<input type=\"hidden\" name=\"remove_photos[]\" value=\"" + PhotoId + "\" />";
    new Insertion.Top('posting_step_2', insertHtml);
  }
  
  if (el.parentNode)
  {
    var id = $A(el.parentNode.id.split('_')).last();
    var forms = $(el.parentNode).siblings();
    
    if (forms.length > 0)
    {
      forms.last().addClassName('last');
      forms.first().removeClassName('more');
      
      Element.remove(el.parentNode);
      Element.show('add_photo');
      var insertHtml = "<input type=\"hidden\" name=\"remove_photos[]\" value=\"" + id + "\" />";
      new Insertion.Top('posting_step_2', insertHtml);
    }
    else
    {
      Form.reset(el.parentNode);
    }
  }

  checkTop();
}

function getPhotos(field) {
  
  var retArr = new Array();
  var photos = $(field).getElementsByClassName('photo');
  var total_photos = 0;
  var photoNumber;

  for(i = 0, c = photos.length; i < c; i++) {
    if(photos[i].value != "" && !photos[i].disabled && photos[i].type != null) {
      photoNumber = photos[i].id.split('_')[1];
      if ($('errorPhoto_' + photoNumber).style.display == 'none')
      {
         retArr.push(photos[i].id);
         total_photos++;
      }
    }
  }
  
  photos_to_upload = total_photos;
  
  return retArr;
}


function showPhotosUploadProgress(total_photos) {

  var myLightbox = new lightboxLT();
  
  getBrowserInfo();
  myLightbox.activate();
    $('photo_total_upload').innerHTML = total_photos;
    myLightbox.processInfoLT($('photos_progress').innerHTML);
    
    $('photos_progress').innerHTML = "";
}

function hidePhotosUploadProgress() {
  
  myLightbox.deactivateLT();
}

function uploadPhotos() {
  
  var photos = getPhotos('field_photos');

  if(photos.length != 0) {
  
    if(display_photos_uploader == true) {
      showPhotosUploadProgress(photos.length);
      display_photos_uploader = false;
    }
  
    var spinner = "&nbsp;&nbsp;<img src='http://images01.olx.com/images/spinner.gif' id='spinner_"+ photos[0] +"' alt='Loading...' width='16' height='16' style='display: none' />&nbsp;";
    new Insertion.After(photos[0], spinner);
    $('upload_form_'+photos[0]).submit();
    
    $('photo_num_uploading').innerHTML = photos_upload_counter;
    photos_upload_counter++;

    $(photos[0]).disabled = 'true';
    Element.show('spinner_'+ photos[0]);
  }
  else {

    if(myLightbox != null) {
      hidePhotosUploadProgress();
    }
  
    submitPostingStep2();
  }
}

function responseUploadPhotos(photoid, error) {
  if(('spinner_'+photoid))
   Element.hide('spinner_'+photoid);
  if(error == 0) {
    new Insertion.After(photoid, "<strong>Ok</strong>");
    photos_ok++;
  }
  else { 
    new Insertion.After(photoid, "<strong>Error</strong>");
  }

  photos_to_upload--;
  
  if(photos_to_upload == 0) { //continue submit
    submitPostingStep2();
  }
  else {
    uploadPhotos();
  }
}

function openModule(params) {

  var ajaxReq = new Ajax.Updater('hidden_content', '/ajax/posting_ajax.php',  
          {method: 'get', parameters: params,
           onComplete: function(){changePostCatgParent()}
          });

  //var transparent_background = $('hidden_transparent_background').style.display = 'block';
  var hidden_container = Element.show('hidden_window');
  
  return $('hidden_window');
}

function closeHiddenWindow() {
  
  //$('hidden_transparent_background').style.display = 'none';
  Element.hide('hidden_window');
  $('hidden_content').innerHTML = '';
}

function changeListingType(el) {
  
  if($('required_login')) {
    if($F(el) == 2) { //CLASSIFIED
      Element.hide('required_login');
      Element.show('div_without_reg');
      Element.show('optional_login');
      $('without_reg').checked="checked" ;
      updateLoginBox(0);
    }
    else {
      Element.hide('div_without_reg');
      Element.show('required_login');
      Element.hide('optional_login');
      $('new_user').checked="checked" ;
      updateLoginBox(0);
    }
  }
  
  $('duration').selectedIndex = -1;
  var durationValue=0;
  if ($('durationValue') && ($F('listingValue')==$F(el)) && ($F('durationValue').length>0) ){
    durationValue = $F('durationValue');
  }

  if($F(el) == 0) { //AUCTION
    if(durationValue==0){
      durationValue=7;
    }
    if($('field_priceC')) Element.hide('field_priceC');
    if($('field_priceB')) Element.hide('field_priceB');
    if($('field_duration')) Element.show('field_duration');
    if ($('duration') && $('duration').options[0].value==3){
      $('duration').remove(0);
    }
    if ($('duration') && $('duration').options[$('duration').length - 1].value==0){
      $('duration').remove($('duration').length - 1);
    }
    $A($('duration').options).each(function(elem){ //por defecto 7days
        if(elem.value==durationValue){
          $('duration').selectedIndex=elem.index;
          
        }
      }
      );
    if($('field_minimum_price')) Element.show('field_minimum_price');
    if($('field_reserve_price')) Element.show('field_reserve_price');
    //if($('field_price')) Element.hide('field_price');
    if($('field_classified_type')) Element.hide('field_classified_type');

  }
  else if($F(el) == 1) { //BUYNOW
    if($('field_priceC')) Element.hide('field_priceC');
    if($('field_priceB')) Element.show('field_priceB');
    if($('field_duration')) Element.hide('field_duration');
    if($('field_minimum_price')) Element.hide('field_minimum_price');
    if($('field_reserve_price')) Element.hide('field_reserve_price');
    //if($('field_price')) Element.show('field_price');
    if($('field_classified_type')) Element.hide('field_classified_type');
  }
  else {
    if($('field_priceC')) Element.show('field_priceC');
    if($('field_priceB')) Element.hide('field_priceB');
    if($('field_duration')) Element.hide('field_duration');
    if ($('duration') && $('duration').options[$('duration').length - 1].value==0){
      $('duration').remove($('duration').length - 1);
    }
    if($('field_minimum_price')) Element.hide('field_minimum_price');
    if($('field_reserve_price')) Element.hide('field_reserve_price');
    //if($('field_price')) Element.show('field_price');
    if($('field_classified_type')) Element.show('field_classified_type');
  }
  checkTop();
}

function validateUsername(username) {
  if ($('new_user') && (username.length >= 6) && $('new_user').checked) {
    new Ajax.Updater('validate_msg', 'checkuserajax.php', { method: 'get', parameters: 'username='+username});
  }
}

function updateLoginBox(check) {
  if($('div_user_new'))
    $('div_user_new').innerHTML='';
  if($('div_user_login'))
    $('div_user_login').innerHTML='';
  
  if ($('new_user') && $('new_user').checked){
    loadTemplateLogin('div_user_new');
    validateUsername($('existing_user').checked ? '' : $F('username'));
    $w('field_password_confirm').each(Element.show);
    /*if($('username'))
      Form.Element.focus('username');*/
  }
  else{
    if($('existing_user') && $('existing_user').checked){
      loadTemplateLogin('div_user_login');
      validateUsername($('existing_user').checked ? '' : $F('username'));
      $w('user_msg passwdMsg').each(Element.hide);
      /*if($('username'))
        Form.Element.focus('username');*/
    }
  }
  if (check)
    checkTop();
}

function loadTemplateLogin(nameObject){
      if($(nameObject)){
        aux=$('existing_user').checked?olxLogin['usernameEmail']:olxLogin['username'];
        $(nameObject).innerHTML =  '<div class="field clearfix" id="field_username"><label for="username" id="msgUsername">'+aux+'</label><div class="control1"><input type="text" name="username" id="username" maxlength="100" size="25" onkeyup="validateUsername(this.value)" /> <span id="validate_msg"></span><span id="user_msg">'+olxLogin['usernameReq']+'</span><span style="display:none;" id="user_blacked" class="error"><br />'+olxLogin['userBlacked']+'</span></div></div>';
        $(nameObject).innerHTML += '<div class="field clearfix" id="field_password"><label for="password" id="msgPassword">'+olxLogin['password']+'</label><div class="control1"><input type="password" name="password" size="25" id="password" onkeyup="validatePassword(this.value)" /><span id="passwdMsg">'+olxLogin['passwdMsg']+'</span><span id="passwdMsgOk" style="display:none;">'+olxLogin['passwdMsgOk']+'</span><span id="passwdMsgError" style="display:none;">'+olxLogin['passwdMsgError']+'</span></div></div>';
        $(nameObject).innerHTML += '<div class="field" id="field_password_confirm" style="display: none;"><label for="password_confirm">'+olxLogin['confirmPassword']+'</label><input type="password" name="password_confirm" size="25" id="password_confirm" onkeyup="validatePasswordConfirm(\'password_confirm\', \'password\')" /><span id="passwdConfMsgError" style="display:none;">'+olxLogin['passwdConfMsgError']+'</span><span id="passwdConfMsgOk" style="display:none;">'+olxLogin['passwdConfMsgOk']+'</span></div></div>';
      }
}  

function getDescriptionValue(descID) {
  
  var description = '';
  var descIframe = $(descID);
  
  if(descIframe.contentWindow.document.body.innerHTML)
    description = descIframe.contentWindow.document.body.innerHTML;
  else
    description = descIframe.contentDocument.body.innerHTML;

  description = description.replace(/^[\s|&nbsp;|\<br\>]*/,'');
  description = description.replace(/[\s|&nbsp;|\<br\>]*$/,'');
  return description;
}

function validatePostingStep2() {
  tinyMCE.triggerSave(true, true);
  $('publish').disabled = true;
  var param = "validate=2&" + Form.serialize($("posting_step_2")) + "&" + Form.serialize($("posting_step_2_2")) ;
  
  new Ajax.Request('/ajax/posting_ajax.php', 
    {
      method: 'post', 
      parameters: param,  
      onComplete: responseValidateStep2,
      onLoading: function() { 
        Element.show('spinner');
      }
    });
}

function responseValidateStep2(resp) {
  removeClassError();

  Element.hide('spinner');
  response = resp.responseText.trim();
  if(response && response.length >0) {
    highlightFieldsWithErrors(response,2);
    $('publish').disabled = false;
  }
  else {
    uploadPhotos();
  }
}

function validateStep3(event,sender) {
  $('publish').disabled = true;
  var param = "validate=3&" + Form.serialize(sender);
  var relTypes = 0;
  Element.show('spinner-publish');
  var relTypes= 0;
  var objectRelType = document.getElementsByName('reltype');

  $A(objectRelType).each(
    function(elem){
      if(elem.checked){
          relTypes = parseInt(relTypes) + parseInt(elem.value);
        }
      });
  param += '&relTypes=' + relTypes;
  new Ajax.Request(
    '/ajax/posting_ajax.php', 
    {
      method: 'get', 
      parameters: param,
      onLoading: function() { Form.disable(this);},
      onComplete: function(resp){
            Element.hide('spinner-publish');
            response = resp.responseText.trim();
            if (!highlightFieldsWithErrors(response,3))
            {
              sender.submit();
            }
            else{
              $('publish').disabled = false;
            }
            Form.enable(this);
      }
    });
    Event.stop(event);
    return false;
}

function highlightFieldsWithErrors(raw_text,step) {
  
  if (raw_text.length>0){
    var fields = $A(raw_text.split(","));
    var err = (fields.length > 0);
    removeErrorHiglights(step);
    
    if(err){
      fields.each(function(s) {
        if ($('field_'+s)){
          $('field_'+s).addClassName('with_errors');
        } else {
          if ($(s)){
            $(s).style.display='';
          }
        }
      });

      if (element = $('errors')) {
        element.show();
        Element.scrollTo(step);
      }
    }
  checkTop();
    return err;
  }
  else{
    return false;
  }
}

function removeErrorHiglights(step)
{
    if(step==2){
      $w('field_reserve_price field_minimum_price field_salary field_experience field_email field_title field_priceC field_priceB field_description field_username field_password field_password_confirm').each(function(id) {
        if($(id)){
        $(id).removeClassName('with_errors');
        }
      });
      $w('email_invalid email_reg user_blacked email_blacked').each(function(id) { if (element = $(id)) element.hide(); });
    }
    else{
      $w('field_areatellfriend field_emailpaypal field_mileage field_weight').each(function(id) {
        if($(id)){
          $(id).removeClassName('with_errors');
        }
      });
    }

}

function removeClassError() {
  if($('errors')) Element.hide('errors');
  
  $w('field_email field_title field_priceC field_priceB field_description field_username field_password field_password_confirm').each(function(id) {
    Element.removeClassName(id, 'with_errors');
  });
}

function changePostCountry(event) {
  changeCountry = 0;
  showAccept = 1;
  if($('additional_error')){
   $('additional_error').innerHTML="";
  }
  if($('additional_selector')){
   $('additional_selector').style.visibility = 'hidden';
  }
  if (event)
    $('country').value = Event.element(event).value;
  
  new Ajax.Request('/ajax/posting_ajax.php', 
    { 
      method : 'get', 
      parameters: 'get_module=3&country='+$F('country')+'&sl='+$F('languageID') + '&sell_session='+$F('sell_session'),
      onComplete: function(resp) {
        if($('additional_selector')){
          $('additional_selector').style.visibility = 'visible';
        }
        var next_element;
        if($('zip')){
          next_element=$('zip');
        }
        else{
          if($('state')){
            next_element = $('state');
          }
          else{
            next_element = $('categoryParent');
          }
        }
        if (next_element)
          next_element.focus();
        changeCountry = 1;
        changePostCatgParent();
      }
    }
  );
  
}

function changePostZip(thisForm) {
  var zipValue = 0;
  if($('zip'))
    zipValue = $('zip').value;
  var country = 0;
  Element.show('spinner-'+'zip');
  $('additional_error').innerHTML="";
  country = $('country').value;
  new Ajax.Request('/ajax/posting_ajax.php',
    { 
      method : 'get', 
      parameters: '&get_module=3&country='+country+'&zip='+zipValue+'&state=0&city=0'+'&sl='+$F('languageID') + '&sell_session='+$F('sell_session'),
      onComplete:
        function() {
          Element.hide('spinner-'+'zip');
          if ($('categoryParent')){
            Form.Element.focus('categoryParent');
          }
          if($('zip') && $('Accept')){ // solucion ante seleccion de zipcode
            if(showAccept == 1) validateChangeRegion(thisForm);
            showAccept = 1;
         }
        }
    }
  );
}

function allowCharsOnly(event) {

  var e = Event.element(event);
  var code = (event.keyCode ? event.keyCode : event.which);
  
  if (code == 13) {
    Event.stop(event);
    return false;
  }
  
  return true;
}

function allowNumbersOnly(event) {

  var e = Event.element(event);
  var code = (event.keyCode ? event.keyCode : event.which);

  if ((code >= 48 && code <= 57) || code == 8 || code == 9 || (code >= 37 && code <= 40)) {
    return true;
  }
  else{
    Event.stop(event);
    return false;
  }
}

function changePostState(event) {
  Element.show('spinner-'+'state');
  var zip="";
  var country = ($('country').value);
  var state = $F(Event.element(event));
  $('additional_error').innerHTML="";
  if ($('city')) {
    Element.hide('city');
    $('city').siblings().each(Element.hide);
  }
  new Ajax.Request('/ajax/posting_ajax.php', 
    { 
      method : 'get',
      parameters: '&get_module=3&country='+country+'&state='+state+'&zip='+zip+'&sl='+$F('languageID') + '&sell_session='+$F('sell_session'),
      onComplete:
          function() {
            if (zip = $('zip')){
              zip.value = '';
            }
            Element.hide('spinner-'+'state');
            changePostCatgParent();
            Form.Element.focus('city');
          }
    }
  );
}

function changePostCatgParent() {
  var optionSelect;
  changeCategory = 0;
  category = $('categoryParent').value;
  if (!category || category.trim().length == 0 || parseInt(category) == 0) category = -2;
  
  if (categories = window['categories_' + category]) {
    var arr = [];
    for (var i=0; i<categories.length; i++) {
      optionSelect = '';
      if ($('categoryID').value == categories[i][0] ){
        optionSelect =' selected=\"selected\" ';
      }
      arr[i] = '<option value=\"' + categories[i][0] + '\"' + optionSelect + '>' + categories[i][1] + '</option>';
    }
    if(arr.length==0){
        if($('subcategory')){
          Element.hide($('subcategory').parentNode);
          $('subcategory').innerHTML = '';
        }
    }
    else{
      if($('subcategory')){
        Element.show($('subcategory').parentNode);
        $('subcategory').innerHTML = '<select id=\"categoryChild\" name=\"categoryChild\"><option value=\"0\" >' + $F('selectSubCategory') + '</option>' + arr.join() + "</select>";
      }
    }
  }
  else{
    if($('subcategory')){
      Element.hide($('subcategory').parentNode);
      $('subcategory').innerHTML = '';
    }
  }
  changeCategory = 1;
}


function onLoadStep1(){
  changePostCountry(null);
}

function validateStep1() {
  var dtDate = new Date();
  sender = $('posting_step_1');
  $('publish').disabled = true;
  Element.show('spinner-'+'continue');
  var param = "validate=1&rnd=" + dtDate.getSeconds() + Form.serialize(sender);
  if($('errors'))
      Element.hide('errors');
  new Ajax.Request(
    '/ajax/posting_ajax.php', 
    {
      method: 'get', 
      parameters: param,
      onComplete: function(transport) {
            Element.hide('spinner-'+'continue');
            if ((script = transport.responseText.trim()).length > 0) {
              //se elimina la clase error de los objetos
              if($('errors')) {
                Element.show('errors');
              }
              var objectPaso1 = "['country','state','zip','city','categoryParent','categoryChild']";
              var objects = $A(eval(objectPaso1));
              objects.each(function(field) {
                  if (elements = $$('label[for="' + field.toString() + '"]')){
                    elements.each(function(element) {
                        element.removeClassName('with_errors');
                    });
                  }
              });
              var errors = $A(eval(script));
              errors.each(function(field) {
                  if (elements = $$('label[for="' + field.toString() + '"]')){
                    elements.each(function(element) {
                        element.className = 'with_errors';
                    });
                  }
              });
              $('publish').disabled = false;
              checkTop();
            }
            else {
              $('publish').disabled = true;
              sender.submit();
            }
      }
  });
    
  return false;
}

function validateChangeCategory(thisForm)
{
  if (changeCategory==0) return false; //para controlar el onchange pudo refrescar
  if (( $F('categoryParent') > 0 ) && ( (!$('categoryChild')) || $F('categoryChild') > 0))  {
    Element.hide('validation_submit');
    updatePostingStep2(thisForm);
  }
  else
  {
    Element.show('validation_submit');
    return false;
  }
}

function validateChangeRegion(thisForm)
{
  if (changeCountry==0) return false; 
  if($('zip') && $('Accept') && showAccept == 0){ //para controlar que el zipcode se valido
    showAccept = 1;
    changePostZip(thisForm);
  }
  else{
    stateCityCase = $F('countryStateCityCase');
    if ( ($('additional_error').innerHTML).length==0  &&
      ( ($('zip') && $F('zip').length > 0) ||
        ((($('state') && $F('state') > 0) && ($('city') && $F('city') > 0)) || (stateCityCase==8))
      )
    )
    {
      Element.hide('validation_submit');
      updatePostingStep2(thisForm);
    }
    else
    {
      Element.show('validation_submit');
      return false;
    }
  }  
}

function updatePostingStep2(thisForm) {
  $('updateSellSession').value = 1;
  $('step').value = 2;
  //Cambio de categoría
  if ($('categoryChild'))
    $('categoryID').value = $F('categoryChild');
  
  else if ($('categoryParent'))
    $('categoryID').value = $F('categoryParent');

  //Cambio de location
  if ($('state'))
    $('stateID').value = $F('state');
  if ($('city'))
    $('cityID').value = $F('city');
  if ($('zip'))
    $('zipCode').value = $F('zip');
  if ($('country'))
    $('countryID').value = $F('country');

  var fieldHidden = "<input type='hidden' value='"+ Form.serialize($('posting_step_2_2')) +"' name='hiddenform'>";
  new Insertion.Top('posting_step_2', fieldHidden);
  //$(thisForm).action = $(thisForm).action + '?' + Form.serialize($('posting_step_2_2')); 
  $(thisForm).submit();
}

function submitPostingStep2() {

  var param = "submit=2&" + Form.serialize($("posting_step_2")) + "&" + Form.serialize($("posting_step_2_2")) + "&imageQty=" + photos_ok;
  
  new Ajax.Request('/ajax/posting_ajax.php', 
    {
      method: 'post', 
      parameters: param,  
      onComplete: responseSubmitStep2
    });
}

function responseSubmitStep2(resp) {
  removeClassError();

  if(resp.responseText == 0) {
    Element.show('errors');
    $('publish').disabled = false;
  } else {
      if($('action_type')) {
        // If is renew item or edit item
        qs_action = "<input type='hidden' name='"+ $F('action_type') +"' value='1'>";

        switch($F('action_type')) {
          case 'edit':
            qs_action += "<input type='hidden' name='editid' value='"+ $F($("posting_step_2").editid) + "'>";
            qs_action += "<input type='hidden' name='sk' value='"+ $F($("posting_step_2").sk) + "'>";
            break;
          case 'renew':
            qs_action += "<input type='hidden' name='itemid' value='"+ resp.responseText + "'>";
            qs_action += "<input type='hidden' name='renewID' value='"+ $F($("posting_step_2").renewID) + "'>";
            qs_action += "<input type='hidden' name='renew_upgrade' value='"+ $F($("posting_step_2").renew_upgrade) + "'>";
            break;
          default:
            qs_action += "<input type='hidden' name='itemid' value='"+ resp.responseText + "'>";
            qs_action += "<input type='hidden' name='sell_session' value='"+ $F($("posting_step_2").sell_session) +"'>";
            break;
        }

      } else {
        qs_action = "<input type='hidden' name='itemid' value='"+ resp.responseText + "'>";
        //Add data to check if the user has registered in this posting
        if ($("posting_step_2_2") && ($("posting_step_2_2").username) && ($("posting_step_2_2").password) ) {
          if (($("posting_step_2_2").new_user.checked) && ($F($("posting_step_2_2").username).length > 0) && ($F($("posting_step_2_2").password).length > 0))
            qs_action += "<input type='hidden' name='newregistration' value='1'>";
          else
          qs_action += "<input type='hidden' name='newregistration' value='0'>";
        }
      }

      document.body.innerHTML += "<form action='"+ $("posting_step_2").getAttribute('action') +"' name='form_gonextstep' method='post'>" +
          "<input type='hidden' name='step' value='3'>" +
          "<input type='hidden' name='updateSellSession' value='"+ $F($("posting_step_2").updateSellSession) +"'>" +
          "<input type='hidden' name='countryID' value='"+ $F($("posting_step_2").countryID) +"'>" +
          "<input type='hidden' name='categoryID' value='"+ $F($("posting_step_2").categoryID) +"'>" +
          

          qs_action  + "</form>";
      document.form_gonextstep.submit();
  }
}

function uploadVideo(sender,url){
  
  if ($F('VE_Path')=='') {
    window.open('/addvideo.php?redir=http://'+url+'/uploaded.php','OLX','width=650,height=370,top=100,left=100,scrollbars=no,status=false');
  } 
  else {
    updateVideo($F('VE_Path')+'&delete');sender.value='';
    $('video_thumb').innerHTML='';
    $('VE_Path').value='';
    document.getElementById('videobutton').value=$F('addVideo');
  }
}

function VE_videouploadedpost(path, duration, src) {
  VE_videouploadededit(path);
}

function VE_videouploadededit(path, duration, src) {
  
  $('VE_Path').value = path;
  updateVideo(path+'&update');
  $('video_form').submit();
}

var data = new Array();

function updateVideo(url){
  if (url!=''){
    data['url']  = url;
    olx_delete();
  }
}

function olx_delete() {
  try {
    var fn = ajax_update;
    fn(data);
  }
  catch(e) {
    setTimeout('olx_delete();',100);
  }
}

function onclickAcceptPaypal(sender) {
  if(sender.checked){
    $('emailpaypal').disabled = false;
    $('emailpaypal').value = $('emailhidden').value; 

  }
  else{
    $('emailpaypal').disabled = true;
  }
}

function onchangePostMake(sender){
  Element.show('spinner-'+'make');
  new Ajax.Updater(
    'divModel',    
    '/ajax/posting_ajax.php', 
    {
      method: 'get', 
      parameters: 'make='+sender.value+'&get_module=5',
      onComplete: function(){ Element.hide('spinner-'+'make');}
    });
}

function onLoadStep3(){
//  This is not needed, however, I don't erase the function just in case.
/*   
   if ($('VE_Path') && $F('VE_Path').length >0){
    $('video_thumb').innerHTML = '<img src=\"' + $F('VE_Path') + '&trumbnail\" border=\"0\" vspace=\"5\"><br>';
    $('videobutton').value = $F('deleteVideo');
   }
*/
}

function onlyNumber(e) {
  
  e = (e) ? e : window.event
    
  var charCode = (e.which) ? e.which : e.keyCode;
  var currValue = Event.element(e).value;

    if (charCode > 31 && (charCode < 48 || charCode > 57) && (charCode != 44) && (charCode != 46)) {
        return false;
    }
    
    //Solo permito una coma o punto
    if ((charCode == 44) || (charCode == 46)) {
      if ((currValue.indexOf(',') > 0) || (currValue.indexOf('.') > 0)) {
        return false;
      }
    }
    
    return true;
}

function validatePassword(pass) {

  if($('new_user').checked) {

    if(pass == "") {
      Element.show('passwdMsg');
      Element.hide('passwdMsgOk');
      Element.hide('passwdMsgError');
    }
    else if(pass.length >= 6) {
      Element.hide('passwdMsg');
      Element.show('passwdMsgOk');
      Element.hide('passwdMsgError');
    }
    else {
      Element.hide('passwdMsg');
      Element.hide('passwdMsgOk');
      Element.show('passwdMsgError');
    }
    
    if($('password_confirm')) {
      validatePasswordConfirm('password_confirm', 'password');
    }
  }
}

function validatePasswordConfirm(passconfid, passid) {

  if($F(passconfid) != $F(passid)) {
    Element.show('passwdConfMsgError');
    Element.hide('passwdConfMsgOk');
  }
  else {
    Element.hide('passwdConfMsgError');
    Element.show('passwdConfMsgOk');
  }
}

var editor_enabled = true;

function toggle_editor(id, enable)
{
  var element = document.getElementById(id);
  
  if (element) {
    if (enable && !window['editor_enabled'] && tinyMCE.getInstanceById(id) == null) {
      Logger.info('Enabling WYSIWYG editor on ' + id + '...');
      initWysiwygEditor();
      tinyMCE.execCommand('mceAddControl', false, id);
      Logger.info('WYSIWYG editor enabled.');
      window['editor_enabled'] = true;
    }
    else if (!enable && window['editor_enabled']) {
      Logger.info('Disabling WYSIWYG editor on ' + id + '...');
      tinyMCE.execCommand('mceRemoveControl', false, id);
      //tinyMCE.execInstanceCommand('mce_editor_0', 'mceCodeEditor', false);
      Logger.info('WYSIWYG editor disabled.');
      window['editor_enabled'] = false;
    }
  }
}

function initWysiwygEditor()
{
  tinyMCE.init({
      mode : 'textareas',
      theme : "advanced",
      theme_advanced_buttons1 : "bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright, justifyfull,bullist,numlist,undo,redo,link,unlink,formatselect,fontselect,fontsizeselect, code",
      theme_advanced_buttons2 : "",
      theme_advanced_buttons3 : "",
      theme_advanced_toolbar_location : "top",
      theme_advanced_toolbar_align : "left",
      width: '680px',
      height: '300px'
  });
}

function loadContent(file){
  

  file = file + $('languageID').value + '.js';
  /*var head = document.getElementsByTagName('head').item(0)
  var scriptTag = document.getElementById('loadScript');
  if(scriptTag) head.removeChild(scriptTag);
  script = document.createElement('script');
  script.src = file;
  script.type = 'text/javascript';
  script.id = 'loadScript';
  head.appendChild(script);*/

  var scriptNode = document.createElement('script');
  scriptNode.type='text/javascript';
  scriptNode.defer=true;
  scriptNode.src=file;
  document.getElementsByTagName('head')[0].appendChild(scriptNode);


}
function imageHide(){
    var browser = navigator.userAgent;// BrowserDetect.browser;
    if(browser.indexOf('Safari') != -1 || browser.indexOf('Konqueror') != -1){
        Element.hide('photospost_container');
    }
}

function addVideoClick(){
  if ($('VE_Path').value){
    $('VE_Path').value = "";
    Element.show('addVideoButton');
    Element.hide('deleteVideo');
    $('video_thumb').innerHTML = "";
  }else
    window.open('/addvideo.php','OLX','width=670,height=370,top=100,left=100,scrollbars=no,status=false');
}
