var IndieSigninForm = Behavior.create({
	initialize: function(ajaxFunc, errClass, condition) {
		this.ajaxFunc = ajaxFunc;
		this.errClass  = errClass  || 'error';
		this.condition = condition || true;
		this.errorMessage  = new Template("<span class='" + this.errClass + "'>#{message}</span>");
	},
	onsubmit: function(event) {
		this.clearErrors();
		
    // Event.stop(event);
    // this.showError("Signing in is not yet enabled.");
    // return false;
		
		if (this.emptyInputs().any()) {
			Event.stop(event);
			this.showError("Please provide an email and password.");
		} else {
			Event.stop(event);
			new Ajax.Request('/sessions/' + this.ajaxFunc, {
				method: 'post',
				parameters: this.element.serialize(true),
				onFailure: function(xhr) {
					this.showError("The email and password provided do not match. Please try again.");
				}.bind(this),
				onSuccess: function(xhr) {
					this.element.submit();
				}.bind(this)
			});
		}
	},
	showError: function(message) {
	  this.element.up('div').down('p').update(this.errorMessage.evaluate({ "message" : message}));
	},
	clearErrors: function() {
		this.element.getElementsBySelector('li.'+this.errClass).invoke('remove');
	},
	emptyInputs: function() {
		return this.element.getInputs('text').select(function(input) {
			return !input.present() && this.condition;
		}.bind(this));
	}
});

var Clipper = function(cntrl, field) {
  this.cntrl = cntrl;
  this.field = field;
  this.clipper = new ZeroClipboard.Client();
  this.clipper.glue(this.cntrl);
  this.id = 'done-' + Math.floor(Math.random() * 10000).toString();
  
  
  this.clipper.addEventListener('onMouseDown', function(event) {
    this.clipper.setText(this.value());
    this.done();
  }.bind(this));
};
Clipper.prototype = {
  done: function(event) {
    if ($(this.id)) {return;};
    this.cntrl.insert({after: this.doneSpan()});
    new Effect.Opacity(this.id, {
          duration: 2.0, 
          from: 1.0, to: 0,
          delay: 2.0,
          afterFinish: function(event) {
            $(this.id).remove();
          }.bind(this)
        });
  },
  
  doneSpan: function() {
    return new Element('span', { 'id': this.id, 'class': 'notice' }).update('Done!');
  },
  
  value: function() {
    return $F(this.field);
  }
};

document.observe('dom:loaded', function() {
  $$('a.copy').each(function(a) {
    new Clipper(a, a.previous('input'));
  });
  $$('input[readonly=readonly]').invoke('observe', 'click', function(event) {
    event.element().select();
  });
});

var CopyToClipboard = Behavior.create({
  initialize: function(flash_ob, field) {
    console.log(this.id('id'));
    this.flash_ob = Element.extend($(flash_ob));
    // this.clipper = new ZeroClipboard.Client();
    // this.clipper.glue(this);
    this.field = $(field);
    this.id = 'done-' + Math.floor(Math.random() * 10000).toString();
  },
  onclick: function(event) {
    Event.stop(event);

    var v = $F(this.field);
    // this.clipper.setText(v);
    
    if (Prototype.Browser.IE) {
      window.clipboardData.setData('Text', v);
    } else {
      this.flash_ob.toClipboard(v);
    }
    if ($(this.id)) {return;};
    new Insertion.After(this.element, '<span id="' + this.id + '" class="notice">Done!</span>');
    new Effect.Opacity(this.id, {
          duration: 2.0, 
          from: 1.0, to: 0,
          delay: 2.0,
          afterFinish: function(event) {
            $(this.id).remove();
          }.bind(this)
        });
  }
});

var ClipboardCopyBox = Behavior.create({
  initialize: function() {
    this.flash_ob = $('clipboardCopy');
    this.field = this.element.previous('input');
    this.id = 'done-' + Math.floor(Math.random() * 10000).toString();
  },
  onclick: function(event) {
    Event.stop(event);
    var v = $F(this.field);

    if (Prototype.Browser.IE) {
      window.clipboardData.setData('Text', v);
    } else {
      this.flash_ob.toClipboard(v);
    }
    if ($(this.id)) {return;};
    this.element.insert({after : '<span id="' + this.id + '" class="notice">Done!</span>'});
    new Effect.Opacity(this.id, {
          duration: 2.0, 
          from: 1.0, to: 0,
          delay: 2.0,
          afterFinish: function(event) {
            $(this.id).remove();
          }.bind(this)
        });
  }
});

var SlidingGrid = Class.create({
  // See CSS class div.sliding-grid in indie_artist.css.
  
  initialize:function(gridContainer){
    this.gridContainer = gridContainer;
    this.gridList = this.gridContainer.down('div.grid').down('ul');
    this.gridItem = this.gridList.down('li'); // For grabbing dimensions only
    this.ctrlPrev = this.gridContainer.down('div.ctrl-prev').down('a');
    this.ctrlNext = this.gridContainer.down('div.ctrl-next').down('a');
    if(this.gridItem && this.ctrlPrev && this.ctrlNext){
      this.ctrlPrev.observe('click',this.slideLeft.bindAsEventListener(this));
      this.ctrlNext.observe('click',this.slideRight.bindAsEventListener(this));
      this.gridItemMargins = parseInt(this.gridItem.getStyle('margin-left')) + parseInt(this.gridItem.getStyle('margin-right'));
      this.gridItemPaddings = parseInt(this.gridItem.getStyle('padding-left')) + parseInt(this.gridItem.getStyle('padding-right'));
      this.gridItemBorders = parseInt(this.gridItem.getStyle('border-left-width')) + parseInt(this.gridItem.getStyle('border-right-width'))
      this.gridItemTotalWidth = parseInt(this.gridItem.getStyle('width'))+this.gridItemMargins + this.gridItemPaddings + this.gridItemBorders;
      this.totalWidth = this.gridItemTotalWidth*this.gridList.select('li').length;
      this.gridList.style.width = this.totalWidth + 'px';
    // this.slideAmt = this.gridItemTotalWidth*6;
      this.slideAmt = parseInt(this.gridContainer.down('div.grid').getStyle('width'));
      this.imagesPerPage = Math.ceil(this.slideAmt / this.gridItemTotalWidth);
      this.currentPage = 1;
      this.maxPage = Math.ceil(this.gridList.select('li').length/this.imagesPerPage)
      this.initExtensions();
    }
  },
  initExtensions:function(){},
  curX:function(){ return parseInt(this.gridList.getStyle('left')) },
  slideLeft:function(ev){
    this.slide(Math.min(0, this.curX()+this.slideAmt));
    this.currentPage--;
    ev.stop();
  },
  slideRight:function(ev){
    if (this.currentPage < this.maxPage) {
      this.slide(this.curX()-this.slideAmt);
      this.currentPage++;
    }
    ev.stop();
  },
  slide:function(x){
    new Effect.Morph(this.gridList,{style:'left:'+x+'px',duration:0.8});
  }
});

var SlidingGridInput = Class.create(SlidingGrid,{
  // Extends SlidingGrid class. This is for use when the grid is part of a
  // form, and the ID of the selected item needs to be captured as part of
  // the form submission.
  
  initExtensions:function(){
    var _this=this;
    this.gridList.select('a').invoke('observe','click',_this.selectMedium.bindAsEventListener(_this));
  },
  selectMedium:function(ev){
    var li=ev.element().up('li.indie-medium'), id=li.id, name='selected_medium', oldInput=null;

    // Unselect all
    this.gridContainer.select('li.indie-medium-selected').invoke('removeClassName','indie-medium-selected');
    
    // Remove input and end (i.e., toggle selection off)
    if(oldInput=this.gridContainer.down('input[value="'+id+'"]')){
      oldInput.remove();
                /* FIXME: Remove test JS */
                // var input=this.gridContainer.down('input[name="'+name+'"]');
                // if(input){
                //   alert('FAILED to remove input! Added: <input type="'+input.type+'" name="'+input.name+'" value="'+input.value+'" />');
                // }else{
                //   alert('Removed input successfully.')
                // }
                /* end test JS */
      ev.stop();return
    }
    
    // Select and add input
    this.gridContainer.select('input[name="'+name+'"]').invoke('remove');
    this.gridContainer.insert({
      bottom:new Element('input',{type:'hidden',name:name,value:id})
    });
    li.addClassName('indie-medium-selected')
              /* FIXME: Remove test JS */
              // var input=this.gridContainer.down('input[name="'+name+'"]');
              // if(input){
              //   alert('Added successfully: <input type="'+input.type+'" name="'+input.name+'" value="'+input.value+'" />');
              // }else{
              //   alert('FAILED to add input');
              // }
              /* end test JS */
    ev.stop();
  }
});

Event.addBehavior({
 '#inline-terms-control' : InlineDropdown('inline-terms'),
 '#difference-artist-partner-pro-control' : InlineDropdown('difference-artist-partner-pro-block'),
 '#what-is-widgetron-control' : InlineDropdown('what-is-widgetron-block'),
 '#easiest-way-add-purchase-control' : InlineDropdown('easiest-way-add-purchase-block'),
 '#how-access-api-control' : InlineDropdown('how-access-api-block'),
 '#free-content-control' : InlineDropdown('free-content-block'),
 '#change-price-control' : InlineDropdown('change-price-block'),
 '#signin' : IndieSigninForm('check_indie_credentials', 'signin-error'),
 '#indie-what-control' : InlineDropdown('indie-what-block'),
 '#indie-who-control' : InlineDropdown('indie-who-block'),
 '#indie-make-money-control' : InlineDropdown('indie-make-money-block'),
 '#indie-get-paid-control' : InlineDropdown('indie-get-paid-block'),
 '#indie-buy-ringtones-control' : InlineDropdown('indie-buy-ringtones-block'),
 '#indie-how-buy-ringtones-control' : InlineDropdown('indie-how-buy-ringtones-block'),
 '#indie-where-control' : InlineDropdown('indie-where-block'),
 '#indie-how-many-control' : InlineDropdown('indie-how-many-block'),
 '#indie-update-profile-control' : InlineDropdown('indie-update-profile-block'),
 '#indie-widget-store-control' : InlineDropdown('indie-widget-store-block'),
 '#indies-how-send-control' : InlineDropdown('indies-how-send-block'),
 '#indies-content-removed-control' : InlineDropdown('indies-content-removed-block'),
 '#indies-suggestions-control' : InlineDropdown('indies-suggestions-block'),
 '#indie-without-subscription-control' : InlineDropdown('indie-without-subscription-block'),
 '#ringtone-details-form-images-toggle' : InlineDropdown('ringtone-details-form-images-block'),
 '#ringtone-details-form-images-close' : InlineDropdown('ringtone-details-form-images-block'),
 '#indie-what-kind-of-content-control' : InlineDropdown('indie-what-kind-of-content-block')
});

document.observe('dom:loaded', function(event) {
  $$('table.price-scheme').each(function(table){
    table.select('tr:nth-child(odd)').invoke('setStyle',{
      'background':'#ceebfa'
    });
  });
  
  $$('div#ringtones-teaser > ul > li:nth-child(odd)').invoke('setStyle', {
    marginRight : '33px'
  });
  
  $$('.fixed-content').invoke('observe', 'keypress', function(event) {
    event.stop();
  });
  
  $$('.fixed-content').invoke('observe', 'keydown', function(event) {
    if (!Prototype.Browser.IE) {return false;}
    event.stop();
  });
  
  $$('div.sliding-grid').each(function(grid){
    slider = new SlidingGridInput(grid);
  });
  
  var indiesProfile=$('indies-profile');
  if(indiesProfile){
    indiesProfile.select('a.terms').invoke('observe','click',function(ev){
      window.open(ev.element().readAttribute('href'), '_blank', 'width=900,height=250');
      ev.stop();
    });
  }
});

var IndieMediaPaginator = Behavior.create({
  initialize : function(href_mod) {
    this.href_mod = 'media/'+href_mod;
  },
  onclick : function(ev) {
    if(ev.element().up('div.pagination')){
      ev.stop();
      if(url = ev.target.href){
        if(url.search(this.href_mod) == -1) {
          url = url.gsub('media', this.href_mod);
        }
        new Ajax.Request(url, {method : 'get'});
      }
      return false;
    }
  }
});

Event.addBehavior({
	'#indie-sale-media' : IndieMediaPaginator('sale'),
	'#indie-promo-media' : IndieMediaPaginator('promo')
});

var RingtoneTitleEditor = Behavior.create({
  initialize : function() {
    this.element.select('.ringtone-title').each(
      function(title) {
        ringtone_id = title.id.split("-")[1]
        indie_id = title.id.split("-")[2]
        new Ajax.InPlaceEditor( title, '/indies/'+indie_id+'/ringtones/'+ringtone_id+'/set_title', {ajaxOptions:{method: 'put'}});
      }
    );
  }
});

document.observe('dom:loaded', function(event) {
  new DefaultValueTextField('indie-about');
  new DefaultValueTextField('indie-influences-0');
  new DefaultValueTextField('indie-influences-1');
  new DefaultValueTextField('indie-influences-2');
  new DefaultValueTextField('indie-influences-3');
});

// Event.addBehavior({
//  '#unpublished-ringtones' : RingtoneTitleEditor
// });

document.observe('dom:loaded',function(){
  (function(){
    ['indies-profile','ringtones-edit','ringtone-details-new'].each(function(id){
      var x=$(id); 
      if(!x || id=='ringtone-details-new' && $('ringtones-edit')){return}
      new IndieMediaForm(
        x.down('fieldset.media-control'),
        x.down('fieldset.media-upload'),
        x.down('fieldset.media-select')
      );
    });
  })();
});

var IndieMediaForm=Class.create({
  // Uses IndieMediaFieldset class
  initialize:function(controlFieldset, uploadFieldset, selectFieldset){
    this.views={
      form:controlFieldset.up('form'),
      fieldsets:{
        control:controlFieldset,
        upload:uploadFieldset,
        select:selectFieldset
      }
    };
    this.observers={
      toggleUpload:this.toggleUpload.bindAsEventListener(this),
      toggleSelect:this.toggleSelect.bindAsEventListener(this)
    };
    
    if(this.views.fieldsets.upload){
      new IndieMediaFieldset(this.views.fieldsets.upload, this);
    }
    if(this.views.fieldsets.select){
      new IndieMediaFieldset(this.views.fieldsets.select, this);
    }
    this.startObservers();
  },
  startObservers:function(){
    this.views.fieldsets.control.down('a.media-upload').observe('click',this.observers.toggleUpload);
    this.views.fieldsets.control.down('a.media-select').observe('click',this.observers.toggleSelect);
    if(this.views.fieldsets.upload){
      this.views.fieldsets.upload.down('span.alt').down('a').observe('click',this.observers.toggleUpload);
    }
    if(this.views.fieldsets.select){
      this.views.fieldsets.select.down('span.alt').down('a').observe('click',this.observers.toggleSelect);
    }
  },
  toggleUpload:function(ev){
    ev.stop();
    if(this.views.fieldsets.upload.visible()){
      this.hideFieldset('upload');
    }else{ this.showFieldset('upload'); this.hideFieldset('select') }
  },
  toggleSelect:function(ev){
    ev.stop();
    if(this.views.fieldsets.select.visible()){
      this.hideFieldset('select');
    }else{ this.showFieldset('select'); this.hideFieldset('upload') }
  },
  showFieldset:function(name){
    if(!this.views.fieldsets[name]){ return }
    this.views.fieldsets[name].appear({duration:0.5})
  },
  hideFieldset:function(name){
    if(!this.views.fieldsets[name]){ return }
    this.views.fieldsets[name].fade({duration:0.5})
  },
  resetFieldset:function(name){
    if(!this.views.fieldsets[name]){ return }
    this.views.fieldsets[name].select('.notice, .error').invoke('remove');
    this.views.fieldsets[name].down('div.submit-remote').show();
    switch(name){
      case 'upload':
        this.views.fieldsets.upload.down('input[type=file]').value=''; break;
      case 'select':/* Anything? */break;
    }
  }
});

var IndieMediaFieldset=Class.create({
  // Used by IndieMediaForm class
  initialize:function(fieldset,mediaForm){
    fieldset=$(fieldset);
    this.mediaForm=mediaForm; // IndieMediaForm
    this.views={
      fieldset:fieldset,
      form:this.mediaForm.views.form,
      submitWrapper:fieldset.down('div.submit-remote')
    };
    this.model={ target:this.views.fieldset.identify()+'-target' };
    this.observers={
      onsubmit:this.onsubmit.bindAsEventListener(this),
      renderSuccess:this.renderSuccess.bindAsEventListener(this),
      renderFailure:this.renderFailure.bindAsEventListener(this)
    };

    this.views.iframe=new Element('iframe',{"class":"hidden", id:this.model.target, name:this.model.target});
    this.views.fieldset.insert({ after:this.views.iframe });
    this.startObservers();
  },
  startObservers:function(){
    this.views.fieldset.down('input[type=submit]').observe('click',this.observers.onsubmit);
    this.views.fieldset.observe('IndieMediaFieldset:renderSuccess',this.observers.renderSuccess);
    this.views.fieldset.observe('IndieMediaFieldset:renderFailure',this.observers.renderFailure);
  },
  onsubmit:function(ev){
    ev.stop();
    
    var loadingText=(this.views.fieldset.match('.media-upload') ? 'Uploading...' : 'Saving...');
    this.views.submitWrapper.select('.notice, .error').invoke('hide');
    this.views.submitWrapper.hide().insert({
      before:new Element('p',{"class":"notice"}).update(loadingText)
    });
    
    // Prepare form to submit to iframe
    this.model.oldTarget=this.views.form.readAttribute('target');
    this.views.form.writeAttribute('action',this.views.form.readAttribute('action')+'.js');
    this.views.form.writeAttribute('target',this.model.target);
    this.views.form.submit();
    setTimeout(function(){
      // Revert form so that the next submit works as usual
      this.views.form.writeAttribute('action',this.views.form.readAttribute('action').gsub(/\.js$/,''));
      this.views.form.writeAttribute('target',this.model.oldTarget)
    }.bind(this),100);
  },
  renderSuccess:function(ev){
    this.mediaForm.views.fieldsets.control.down('div.image').down('img')
      .writeAttribute('src',ev.memo.imagePath);
    this.mediaForm.views.fieldsets.control.select('.notice, .error').invoke('remove');
    this.mediaForm.views.fieldsets.control.down('div.controls').insert({
      bottom:new Element('p',{"class":"notice"}).update(ev.memo.notice)
    });
    this.mediaForm.hideFieldset('upload'); this.mediaForm.resetFieldset('upload');
    this.mediaForm.hideFieldset('select'); this.mediaForm.resetFieldset('select');
  },
  renderFailure:function(ev){
    this.views.submitWrapper.show().insert({
      before:new Element('div',{"class":"error"}).update(ev.memo.error)
    });
  }
});

function paypalOrCheck() {
 var link;
 if (link = $('paypal-or-check')) {
   link.observe('click', function(ev){
     var paypal = $$('li.paypal');
     var check = $$('ol.address-list');
     if (paypal && check){
       [ check ].invoke('invoke', 'toggle');
       paypal.invoke('toggle');
     }
     var link = ev.element();
     if (link.innerHTML == "I'd rather be paid by checks through the mail"){
       link.update("PayPal");
     }else{
       link.update("I'd rather be paid by checks through the mail");
     }
     ev.stop();
   });
 }
}
function phoneAutoTab(id_base){
	var input;
	for(var i=0;i<3;i++){
		if(input=$(id_base+'-'+i)){
			input.setAttribute('autocomplete','off');
			input.observe("keyup",function(ev){
  			var filter = [0,8,9,16,17,18,37,38,39,40,46];
				var input = ev.element();
				var key = ev.keyCode;
				if(input.value.length == input.readAttribute('maxlength') && filter.indexOf(key) == -1){
					input.value = input.value.slice(0,input.readAttribute('maxlength'));
					var next=input.next('input');
					if(typeof next != 'undefined' && next.visible()){
						next.focus();
					}
				}
			})
		}
	}
}