var Category = {
  categories: [],
  
  check:function(e){          
    var elm = Event.element(e);
    var regpaid = /\(PAID LISTING \- \$(\d+?)\)/;
    var fee = 0;
    var cat = null;
    
    var opts = $('post_category').select('option');
    var sel = $('post_category').options[$('post_category').selectedIndex];

    //revert any changes to innerHTML name for all categories
    opts.each(function(opt){ $(opt).update(opt.readAttribute('alt')) });    
    //change the currently selected option to reflect upper and lower categories
    sel.update(sel.up('optgroup').readAttribute('label') + ' - ' + sel.text);    
    
    
    // if(elm.options[elm.selectedIndex].text.match(regpaid)) {
    //   fee = elm.options[elm.selectedIndex].text.match(regpaid)[1];                
    // }
    // Post.update_cart(elm, 'cfee', fee);
    this.categories.each((function(c){
      if(c.id == elm.options[elm.selectedIndex].value) {
        fee = c.price || fee;
        cat = c;
        $break;
      }
    }));
    // Post.update_cart(elm, 'cfee', fee);
    
    // eco stuff ... if type == item 
    (cat && cat.category_type == "2") ? $('post_eco').hide() : $('post_eco').show();
    
    // price stuff
    if(elm.options[elm.selectedIndex].text == "free") {
      $('post_price').disabled = true;
      $('post_price').value = "free";
      $('post_price').removeClassName("validate_numeric validate_error");
      $('post_price').addClassName("price_free");                
    } else {
      $('post_price').disabled = false;
      $('post_price').removeClassName("price_free");
      $('post_price').addClassName("validate_numeric");
    }        

    if(cat && cat.category_type == "2"){ // type == service 
      $('post_price').hide();
      $('price_free_wrap').hide();      
      $('post_price').up('.field').previous('label').update("set compensation");
      $('post_price').previous('.price_signage').hide();
      $('post_compensation').show();
      // $('post_compensation').up('.field').previous('h3').show();
      if($('post_register_check_wr')) $('post_register_check_wr').hide();
    } else {
      $('post_price').show();
      $('price_free_wrap').show();
      $('post_price').up('.field').previous('label').update("set a price");
      $('post_price').previous('.price_signage').show();
      $('post_compensation').hide();
      // $('post_compensation').up('.field').previous('h3').hide();
      if($('post_register_check_wr')) $('post_register_check_wr').show();
    }
    
    // alerts stuff
    $$('.alerts').invoke('hide');
    var id = $F('post_category');
    if(el = $('alert_'+id)){
      Effect.BlindDown(el,{duration:0.3});
    }

    // show/hide referrals form
    $('referrals_wrapper').hide();
    $$('.referrals_'+id).invoke('show');                              
  },
  
  free:function(el){
    // price stuff
    el = $(el);
    if(el.checked) {
      $('post_price').disabled = true;
      $('post_price').value = "free";
      $('post_price').removeClassName("validate_numeric validate_error");
      $('post_price').addClassName("price_free");                
    } else {
      $('post_price').disabled = false;
      $('post_price').value = "";
      $('post_price').removeClassName("price_free");
      $('post_price').addClassName("validate_numeric");
    }            
  }
}

// ==============================================================================================================================

var ImageUpload = {
  uploading: false,
  destroy_id: null,
  submit:function(){
    this.uploading = true;
    $('new_image').submit();
    $('image_field','image_loading').invoke('toggle');
  },
  load:function(){
    if(!this.uploading) return;
    this.insert(window.image_target.document.body.innerHTML);
    this.uploading = false;
    $('image_field','image_loading').invoke('toggle');
  },
  
  insert:function(data){
    
    $('images','uploaded_images').invoke('insert',data);
    LB.updateImageList();
  },
  
  confirm_destroy:function(id){
    this.destroy_id = id;
    Effect.BlindDown('confirm_destroy_image',{duration:0.3});
  },
  cancel_destroy:function(){
    Effect.BlindUp('confirm_destroy_image',{duration:0.3});
  },
  destroy:function(id){
    var el = $('image_'+this.destroy_id);
    el.fade({afterFinish:function(){el.remove()}});
    new Ajax.Request('/images/'+this.destroy_id, {
      method:'delete'
    });
    this.cancel_destroy();
  },
  
  show_load:function(el){
    Element.clonePosition( $('new_image').up(), $('images_title').next(), {setWidth:false, setHeight:false} )
    $('images_title').next().setStyle({visibility:'hidden'})
    $('new_image').up().show();
  },
  
  show_snap:function(){
    Popin.load('/images/webcam');
  },
  
  show_upload:function(){
    Popin.load('/images/upload');
  }
}

// ==============================================================================================================================

var Post = {
  fees: 0,    
  premium_fee: 0,
  category_fee: 0,
  discount:0,
  attributes:{},
  init:function(attributes){
    this.attributes = attributes || {};
    // this.set_premium(this.attributes.premium);
    this.set_premium(this.attributes.requested_premium_id);
    this.check_promo();
    new Form.Element.Observer('coupon_code', 0.4, this.check_promo)
  },
  
  set_premium:function(on){
    if(on){
      $('standard_post_checkbox').focus(); 
      $('premium_post_checkbox').checked=true; 
      $('post_new_tabs','post_new_info_wr').invoke('removeClassName','post_new_standard'); 
      $('standard_post_checkbox').checked=false;
    } else {
      $('standard_post_checkbox').focus(); 
      $('standard_post_checkbox').checked=true; 
      $('post_new_tabs','post_new_info_wr').invoke('addClassName','post_new_standard'); 
      $('premium_post_checkbox').checked=false;
    }
  },

  log_reg:function(){
    if($('need_account').checked){
      $('register').show();
      $('login').hide();
    } else {
      $('login').show();
      $('register').hide();
    }
  },
  
  check_promo:function(){
    if($F('coupon_code').strip() == "") {
      $('promo_status').update('');
      return;
    }
    new Ajax.Request('/check_promo_code', {parameters:{code:$F('coupon_code'), post_id:this.attributes.id}, evalScripts:true});
  },
  
  apply_promo:function(discount){
    this.discount = discount / 100.0;
    this.update_total('billing_options');
    if(this.discount > 0) $('promo_status').update(discount+"% off");
  },
  
  reject_promo:function(msg){
    this.apply_promo(0);
    $('promo_status').update( msg || 'not found');
  },

  update_cart:function(el, type, fee){
    if(!isNaN(fee) && type.match(/pfee|cfee/)) {
      fee = parseFloat(fee);
      
      if(type == "pfee") this.premium_fee = Math.max(fee, 0);
      if(type == "cfee") this.category_fee = Math.max(fee, 0);

      if(fee > 0) $('billing').show();
      this.update_total( fee>0 ? 'billing_options' : '' );
      // this.update_total();
    } else
      alert('dont be screwy');      
  },
  
  update_total:function(el){      
    var sub = this.premium_fee + this.category_fee;
    this.fees = sub - (sub * this.discount);
    
    $('totals').update( this.fees.toFixed(2).toString() );
    
    //el = $(el) ? el : 'billing'      
    //this.fees <= 0 ? $(el).hide() : $(el).show();      
  },
   
  submit:function(){
    this.toggle_loading();
    if(!Val.validate('post_form')) {
      this.toggle_loading();        
      
      $('invalid_post_msg').down('img.icon_alert').next('span').
        update('sorry, you\'re missing some info about your post,<br /> please see the errors highlighted in red above.')
      
      Effect.BlindDown('invalid_post_msg');
      
      // IE hack to coax out validation messages for inputs in a table cell
      $$('.validate_error_msg').each((function(el){ Effect.Pulsate(el, {pulses: 1, duration: 1}) }));
      return false;
    }
    
    if(!logged_in()){
      this.toggle_loading();
      Effect.BlindUp('invalid_post_msg');
      Popin.load('/profiles/new?after=Post.submit()');
      return false;
    }
    
    ClickClear.cleary();
    try{$('post_confirmation').value = $F('confirmation_check_box')}catch(e){}
  
    new Ajax.Request($('post_form').readAttribute('action'), 
      {asynchronous:true, evalScripts:true, parameters:Form.serialize('post_form')}); 
    return false;
  },
  
  toggle_loading:function(){$('create_post_btn','post_loading').invoke('toggle')},
  
  list:function(){
    Popin.alert('<img src="/images/loading.gif"/> One moment please...');
    $('pay_form').submit();
  }
}

function forgot_password(e){
  el = Event.element(e);
  
  if(Val.validate('invalid_post_msg')) {
    $($('forgot_email'), $('forgot_email').next('input'), $('forgot_email').next('img')).invoke('toggle');
    new Ajax.Updater(el.up('.post_alerts_text'), '<%= forgot_path %>',{
      method:'get', evalScripts:true, parameters:{email:$F('forgot_email')}
    });      
  }
}

// ==========================================================================================================

var Referrals = {
  remove:function(e){
    var el = Event.element(e);
    el.up('.referral_form').remove();
  },
  add:function(e){
    var el = $$('.referral_form').first().cloneNode(true);
    $('referrals').insert(el);
    el.select("input").each(function(el){el.value = "";});
    ClickClear.init(el);
  }
}