var BuyObjects = {mp3: null, wma: null};

var _User = Class.create();
_User.prototype = {
  initialize: function() {
		this.ban = { track : { wma : null, mp3 : null }, album : { wma : null, mp3 : null } };
		this.url = { track : { wma : "/download/check_ban?type=wmatrack", mp3 : null }, 
								 album : { wma : "/download/check_ban?type=wmaalbum", mp3 : null } };
	},
	check: function(subject, format){
		new Ajax.Request(this.url[subject][format], {onSuccess: function(xhr){
			try{
				var response = xhr.responseText.evalJSON();
			}catch(e){}
			if(response){ 
				this.ban[subject][format] = response; 
			}
		}.bind(this)});
	},
	checkUserStatus: function(ban){
		if(!(ban && ban.status)){return true;}
		switch(ban.status){
		case 'banned':
			if( $("error-message") ){
				$("error-message-content").update(ban.text);
				showMessage($("error-message").innerHTML);
			}
			return false;
		case 'members_only':
			if($("login-to-continue")){
				showMessage($("login-to-continue").innerHTML);
			}
			return false;
		default:
			break;
		}		
		return true;
	}
};
var User = new _User();
var BuyWma = Class.create();
BuyWma.prototype = {
  initialize: function(neverAsk) {
		this.format = "wma";
		this.neverAsk = neverAsk;
		BuyObjects[this.format] = this;
    this.setScenario();
	},
  setScenario: function(){
		this.scenario = this.neverAsk ? {errorMessage : Buy.dialogs[3], albumOnly : Buy.dialogs[11]} : 
			{errorMessage : Buy.dialogs[3], buyWma : Buy.dialogs[4], albumOnly : Buy.dialogs[11]};
	},
	requestTrack: function(track){ 
		if(track.container.hasClassName("karma")){
			if(AlbumTabs){AlbumTabs.switchTabs(null, "tabmp3");}
  		try {
  			newBuyObjects[User.logged ? "logged" : "notlogged"].mp3.requestTrack(track);
				return true;
  		}catch(e){};
		}
		User.check("track", this.format);
		if(!User.checkUserStatus(User.ban.track[this.format])){	
			return false;			
		}
		var dialog = track.container.hasClassName(Buy.state.albumOnly) ? this.scenario.albumOnly : this.scenario.buyWma; 
		if(dialog){
			if($(dialog)){
				$(dialog).down("form").action = track[this.format].url;
        try{$(dialog).down("em").innerHTML = track[this.format].title;}catch(e){}
				showMessage($(dialog).innerHTML);
			}
		}
	},
	getKarmaTrack: function(track){
		var karmaBalance = $("karmaBalance") ? !!parseFloat($("karmaBalance").innerHTML) : false;
		var dialogId = "karmaTrack" + (karmaBalance ? "-get-": "-buy-") +this.format;
		var dialog = $(dialogId);
		var form = dialog.down("form");
		try{
			mp3Tracks.trackThroughDialog = track;
			if(!karmaBalance){
				form.action = track[this.format].url;
			}
		}catch(e){}
		var mesTemplate = new Template(dialog.innerHTML);
		showMessage(mesTemplate.evaluate({TrackTitle: track[this.format].title}));
	},
	submitWma: function(form){
    form.target = "downloadFrame";
    this.neverAsk = form.elements["buy_reminder"].checked;
		this.scenario = this.neverAsk ? {} : { buyWma : Buy.dialogs[4]};
    closeDialog();
    if(this.neverAsk){
      var pars = Form.serialize(form);
      new Ajax.Request(Buy.url.buyTrack, {
				parameters: pars 
			});
    }
    return true;
	}
};
var BuyAlbumWma = Class.create();
BuyAlbumWma.prototype = {
  initialize: function() {
		this.format = "wma";
		if($("buy-album") && $("buy-album").down("a."+this.format)){
			this.albumButton = $("buy-album").down("a."+this.format);
		}else {return false;}
		this.scenario = {errorMessage : Buy.dialogs[3], buyAlbum : Buy.dialogs[8]};
	},
	requestAlbum: function(){
  	var dialog = $(this.scenario.buyAlbum);
		if(!dialog){return false;}
    showMessage(dialog.innerHTML);
    return;
    /*
    User.check("album", this.format);
		if(!User.checkUserStatus(User.ban.album[this.format])){	
			return false;			
		}
		
		if(this.scenario.buyAlbum){
			var dialog = $(this.scenario.buyAlbum);
			if(dialog){ var form = dialog.down("form"); }
			if(!form){return false;}
			$("wma-download-zip-sku").value = Album.sku;
			$("wma-download-zip-type").value = this.format;
			dialog.getElementsByTagName("em")[0].innerHTML = Album.title;
			showMessage(dialog.innerHTML);
		}
		*/
	}
};
var BuyTrack = Class.create();
BuyTrack.prototype = {
  initialize: function(format, neverAsk) {
		this.neverAsk = neverAsk;
		this.format = format;
		this.setScenario();
		this.trackThroughDialog = null;
	},
	setScenario: function(){
		this.scenario = this.neverAsk ? 
					{ errorMessage : Buy.dialogs[3], requestProcessing : Buy.dialogs[2], insufficientBalance : Buy.dialogs[5], albumOnly : Buy.dialogs[10]} : {
						buyTrack : Buy.dialogs[0], 
						requestProcessing : Buy.dialogs[2],
						errorMessage : Buy.dialogs[3],
						insufficientBalance : Buy.dialogs[5],
						downloadTrack : Buy.dialogs[6],
						albumOnly : Buy.dialogs[10]
					};
	},
	requestTrack: function(track){ 
    if(track[this.format].element.hasClassName(Buy.state.bought)){
      this.scenario = {};
      this.download(track);
      return true;
    }
		if(track[this.format].element.hasClassName(Buy.state.processing)){return false;}
		if(track.container.hasClassName("karma")){
			this.getKarmaTrack(track);
			return true;
		}else if(Buy.isNovice()){
			return true;
		}else if(track.container.hasClassName(Buy.state.albumOnly)){
			showMessage($(this.scenario.albumOnly).innerHTML);
			return true;
		}
		if(this.scenario.buyTrack){
			if($(this.scenario.buyTrack)){
				this.trackThroughDialog = track;
				$(this.scenario.buyTrack).getElementsByTagName("em")[0].innerHTML = track[this.format].title;
				showMessage($(this.scenario.buyTrack).innerHTML);
			}
		}else{
			this.buyTrack(track); 
		}
	},
	getKarmaTrack: function(track){
		var karmaBalance = $("karmaBalance") ? parseFloat($("karmaBalance").innerHTML) : 0;
		var dialogId = "karmaTrack" + (karmaBalance ? "-get-": "-buy-") +this.format;
		var dialog = $(dialogId);
		this.trackThroughDialog = track;
		var mesTemplate = new Template(dialog.innerHTML);
		showMessage(mesTemplate.evaluate({TrackTitle: track[this.format].title}));
	},
  buyFromDialog: function(form) {
		try{
		if(this.neverAsk != form.elements["buy_reminder"].checked){
			this.neverAsk = form.elements["buy_reminder"].checked;
			this.needChangeTrackScenario = true;
		}
		}catch(e){}
		this.buyTrack(this.trackThroughDialog);
  },
	buyTrack: function(track){
		var pars = "track_id="+track.id;
		if(!this.neverAskSent && this.neverAsk){ pars+= "&buy_reminder=on"; this.neverAskSent = true;}
    new Ajax.Request(Buy.url.buyTrack, {
				parameters: pars,
				onFailure: function(track, xhr){ this.error(track, xhr.status); }.bind(this, track),
				onSuccess: this.buyTrackAnswer.bind(this, track)
			});
		Buy.updateTrack(track, this.format, Buy.state.processing);
		if(this.scenario.requestProcessing && $(this.scenario.requestProcessing)){
			showMessage($(this.scenario.requestProcessing).innerHTML);
		}
	},
  buyTrackAnswer: function (track, xhr){
		try{
			var response = xhr.responseText.evalJSON();
		}catch(e){}
		if(response && response.status && response.status == "ok" && response.id){
			var track_id = response.id;
			if(track.id != track_id){ track = Album.tracks.find(function(track){ return (track.id == track_id); }); }
			Buy.updateTrack(track, this.format, Buy.state.bought);
			if(track.container.hasClassName("karma")){
				Buy.updateTrack(track, "wma", Buy.state.bought);
				track["wma"].element.down("a.buy").href = track["wma"].element.down("a.track").href = track["wma"].url = track[this.format].url;
			}
			Buy.updateBalance(response);
			this.download(track);
		}else if(response && response.status && response.status == "error" && response.number){
			Buy.updateBalance(response);
			this.error(track, response.number);
		}else{ this.error(track); }
		if(this.needChangeTrackScenario){ this.setScenario(); this.needChangeTrackScenario = false;}
		
  },
	download: function(track){
		var dialog = $("download-track-message");
		if(dialog){ var form = dialog.down("form"); }else{ closeDialog(); }
		if(!form){return false;}
		form.target = "downloadFrame";
		form.action = track[this.format].url;
		if(this.scenario.downloadTrack){
			showMessage(dialog.innerHTML);
		}else{
			form.submit();
			closeDialog();
		}
	},
	error: function(track, status) {
		track[this.format].element.removeClassName(Buy.state.processing);
		Buy.error(this, status);
  }
	
};
var BuyAlbum = Class.create();
BuyAlbum.prototype = {
  initialize: function(format, neverAsk) {
		this.neverAsk = neverAsk;
		this.format = format;
		if($("buy-album") && $("buy-album").down("a."+this.format)){
			this.albumButton = $("buy-album").down("a."+this.format);
		}else {return false;}
		this.setScenario();
	},
	setScenario: function(){
		this.scenario = this.neverAsk ? 
					{ errorMessage : Buy.dialogs[3], insufficientBalance : Buy.dialogs[5]} : {
						buyAlbum : Buy.dialogs[1],
						requestProcessing : Buy.dialogs[2],
						errorMessage : Buy.dialogs[3],
						insufficientBalance : Buy.dialogs[5],
						downloadAlbum : Buy.dialogs[7]
					};
	},
  requestAlbum: function (){ 
		if(this.albumButton.hasClassName(Buy.state.bought)){
      this.scenario = {};
      this.download();
      return true;
    }
		if(this.albumButton.hasClassName(Buy.state.processing)){return false;}
		if(Buy.isNovice()){return true;}
    if(this.scenario.buyAlbum){
			if($(this.scenario.buyAlbum)){
				$(this.scenario.buyAlbum).getElementsByTagName("em")[0].innerHTML = Album.title;
				$(this.scenario.buyAlbum).getElementsByTagName("em")[1].innerHTML = Album.artist;
				showMessage($(this.scenario.buyAlbum).innerHTML);
			}
		}else{
			this.buyAlbum();
		}
  },
  buyAlbum: function (){
    this.showAlbumProcess();
    new Ajax.Request(Buy.url.buyAlbum+Album.sku, {
				onFailure: function(xhr){ this.error(xhr.status); }.bind(this),
        onSuccess: this.buyAlbumAnswer.bind(this)});
  },
  showAlbumProcess: function(){
    this.albumButton.addClassName(Buy.state.processing);
    Album.tracks.each(function(track){
			if(!(track[this.format].element.hasClassName(Buy.state.processing) || track[this.format].element.hasClassName(Buy.state.bought))){
        Buy.updateTrack(track, this.format, Buy.state.processing);
      }
    }.bind(this));
		if(this.scenario.requestProcessing && $(this.scenario.requestProcessing)){
			showMessage($(this.scenario.requestProcessing).innerHTML);
		}
	},
  buyAlbumAnswer: function (xhr){
		try{
			var response = xhr.responseText.evalJSON();
		}catch(e){}
    if(response && response.status && response.status == "ok"){
			Album.tracks.each(function(track){
				if(!track[this.format].element.hasClassName(Buy.state.bought)){
					Buy.updateTrack(track, this.format, Buy.state.bought);
				}
			}.bind(this));
			this.albumButton.addClassName(Buy.state.bought);
			Buy.updateBalance(response);
			//closeDialog();
			this.download();
		}else if(response && response.status && response.status == "error" && response.number){
			Buy.updateBalance(response);
			this.error(response.number);
		}else{ this.error(); }
  },
	download: function(){
		var dialog = $("download-album-message");
		if(dialog){ var form = dialog.down("form"); }
		if(!form){return false;}
		$("download-zip-sku").value = Album.sku;
		$("download-zip-type").value = this.format;
		if(this.scenario.downloadAlbum){
			showMessage(dialog.innerHTML);
		}else{
			form.submit();
		}
	},
	error: function(status) {
		this.albumButton.removeClassName(Buy.state.processing);
    Album.tracks.each(function(track){
      track[this.format].element.removeClassName(Buy.state.processing);
    }.bind(this));
		Buy.error(this, status);
  }
};
var AlbumTabs = null;
function initAlbumTabs (currentTab){
	AlbumTabs = new Tabs(["tabmp3", "tabwma", "tabgift"], [Album.sku, "albumTabs", "buy-album", "awesomedeal"], currentTab);
}

var GiftTrack = Class.create();
GiftTrack.prototype = {
  initialize: function(format, neverAsk) {
		this.neverAsk = neverAsk;
		this.format = format;
		this.setScenario();
		this.trackThroughDialog = null;
    this.giftEmail = null;
	},
	setScenario: function(){
		this.scenario = this.neverAsk ? 
					{ errorMessage : Buy.dialogs[3], requestProcessing : Buy.dialogs[2], insufficientBalance : Buy.dialogs[5], albumOnly : Buy.dialogs[10]} : {
						buyTrack : "buy-gift", 
						requestProcessing : Buy.dialogs[2],
						errorMessage : Buy.dialogs[3],
						insufficientBalance : Buy.dialogs[5],
						downloadTrack : "send-gift-message",
						albumOnly : "album-only-gift",
            emailError: "error-email-gift"
					};
	},
	requestTrack: function(track){ 
		if(track.container.hasClassName("karma")){
			this.getKarmaTrack(track);
			return true;
		}else if(Buy.isNovice()){
			return true;
		}else if(track.container.hasClassName(Buy.state.albumOnly)){
			showMessage($(this.scenario.albumOnly).innerHTML);
			return true;
		}
		if(this.scenario.buyTrack){
			if($(this.scenario.buyTrack)){
				this.trackThroughDialog = track;
        this.giftEmail = null;
				$(this.scenario.buyTrack).getElementsByTagName("em")[0].innerHTML = track[this.format].title;
				showMessage($(this.scenario.buyTrack).innerHTML);
			}
		}else{
			this.buyTrack(track); 
		}
	},
	getKarmaTrack: function(track){
		var dialog = $("karmaTrack-get-gift");
		this.trackThroughDialog = track;
    this.giftEmail = null;
		var mesTemplate = new Template(dialog.innerHTML);
		showMessage(mesTemplate.evaluate({TrackTitle: track[this.format].title}));
	},
  saveGiftEmail: function(form){
    this.giftName = $(form).getInputs("text")[0].value;
    this.giftEmail = $(form).getInputs("text")[1].value;
    if(!(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/.test(this.giftEmail))){
      try{new Effect.Highlight($(form).getInputs("text")[1], {queue: {position:'end', scope: "giftEmailValidation", limit:1}, duration: 0.4, startcolor: "#EB26A3"});} catch(e){}
      return false;
    }
    this.giftText = $(form).getElementsByTagName("textarea")[0].value;
    showMessage($('confirm-gift').innerHTML.interpolate({track: this.trackThroughDialog[this.format].title, name: this.giftName, email: this.giftEmail, text:this.giftText.gsub( "\n", "<br />")})); 
  },
  buyFromDialog: function(form) {
		try{
		if(this.neverAsk != form.elements["buy_reminder"].checked){
			this.neverAsk = form.elements["buy_reminder"].checked;
			this.needChangeTrackScenario = true;
		}
		}catch(e){}
		this.buyTrack(this.trackThroughDialog);
  },
	buyTrack: function(track){
		var pars = "track_id="+track.id+"&email="+this.giftEmail+"&text="+this.giftText+"&name="+this.giftName;
		if(!this.neverAskSent && this.neverAsk){ pars+= "&buy_reminder=on"; this.neverAskSent = true;}
    new Ajax.Request(Buy.url.giftTrack, {
				parameters: pars,
				onFailure: function(track, xhr){ this.error(track, xhr.status); }.bind(this, track),
				onSuccess: this.buyTrackAnswer.bind(this, track)
			});
    track[this.format].element.className = this.format + " " + Buy.state.processing;
		if(this.scenario.requestProcessing && $(this.scenario.requestProcessing)){
			showMessage($(this.scenario.requestProcessing).innerHTML);
		}
	},
  buyTrackAnswer: function (track, xhr){
    try{
			var response = xhr.responseText.evalJSON();
		}catch(e){}
		if(response && response.status && response.status == "ok"){
      track[this.format].element.className = this.format;
			Buy.updateBalance(response);
			this.download(track);
		}else if(response && response.status && response.status == "error" && response.number){
      this.error(track, response.number, response.message);
		}else{ this.error(track); }
		if(this.needChangeTrackScenario){ this.setScenario(); this.needChangeTrackScenario = false;}
		
  },
	download: function(track){
		if(this.scenario.downloadTrack){
			showMessage($(this.scenario.downloadTrack).innerHTML.interpolate({email: this.giftEmail}));
		}else{
			closeDialog();
		}
	},
	error: function(track, status, message) {
		track[this.format].element.removeClassName(Buy.state.processing);
		Buy.error(this, status, message);
  }
};

var GiftAlbum = Class.create();
GiftAlbum.prototype = {
  initialize: function(format, neverAsk) {
		this.neverAsk = neverAsk;
		this.format = format;
		if($("buy-album") && $("buy-album").down("a."+this.format)){
			this.albumButton = $("buy-album").down("a."+this.format);
		}else {return false;}
		this.setScenario();
	},
	setScenario: function(){
		this.scenario = this.neverAsk ? 
					{ errorMessage : Buy.dialogs[3], insufficientBalance : Buy.dialogs[5]} : {
						buyAlbum : "buy-album-gift",
						requestProcessing : Buy.dialogs[2],
						errorMessage : Buy.dialogs[3],
						insufficientBalance : Buy.dialogs[5],
						downloadAlbum : "send-gift-album-message",
            emailError: "error-email-album-gift"
					};
	},
  requestAlbum: function (){ 
		if(Buy.isNovice()){return true;}
		if(this.scenario.buyAlbum){
			if($(this.scenario.buyAlbum)){
				$(this.scenario.buyAlbum).getElementsByTagName("em")[0].innerHTML = Album.title;
				showMessage($(this.scenario.buyAlbum).innerHTML);
			}
		}else{
			this.buyAlbum();
		}
  },
  saveGiftEmail: function(form) {
    this.giftName = $(form).getInputs("text")[0].value;
    this.giftEmail = $(form).getInputs("text")[1].value;
    if(!(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/.test(this.giftEmail))){
      try{new Effect.Highlight($(form).getInputs("text")[1], {queue: {position:'end', scope: "giftEmailValidation", limit:1}, duration: 0.4, startcolor: "#EB26A3"});} catch(e){}
      return false;
    }
    this.giftText = $(form).getElementsByTagName("textarea")[0].value;
    showMessage($('confirm-album-gift').innerHTML.interpolate({album: Album.title, name: this.giftName, email: this.giftEmail, text:this.giftText.gsub( "\n", "<br />")})); 
  },
  buyAlbum: function (){
    this.showAlbumProcess();
		var pars = "sku="+Album.sku+"&email="+this.giftEmail+"&text="+this.giftText+"&name="+this.giftName;
    new Ajax.Request(Buy.url.giftTrack, {
				parameters: pars,
				onFailure: function(xhr){ this.error(xhr.status); }.bind(this),
        onSuccess: this.buyAlbumAnswer.bind(this)});
  },
  showAlbumProcess: function(){
    this.albumButton.addClassName(Buy.state.processing);
    Album.tracks.each(function(track){
			if(!(track[this.format].element.hasClassName(Buy.state.processing) || track[this.format].element.hasClassName(Buy.state.bought))){
        track[this.format].element.className = this.format + " " + Buy.state.processing;
      }
    }.bind(this));
		if(this.scenario.requestProcessing && $(this.scenario.requestProcessing)){
			showMessage($(this.scenario.requestProcessing).innerHTML);
		}
	},
  buyAlbumAnswer: function (xhr){
		try{
			var response = xhr.responseText.evalJSON();
		}catch(e){}
		if(response && response.status && response.status == "ok"){
			Album.tracks.each(function(track){
				if(!track[this.format].element.hasClassName(Buy.state.bought)){
          track[this.format].element.className = this.format;
				}
			}.bind(this));
      this.albumButton.removeClassName(Buy.state.processing);
			Buy.updateBalance(response);
			this.download();
		}else if(response && response.status && response.status == "error" && response.number){
			this.error(response.number, response.message);
		}else{ this.error(); }
  },
	download: function(){
		if(this.scenario.downloadAlbum){
			showMessage($(this.scenario.downloadAlbum).innerHTML.interpolate({email: this.giftEmail}));
		}else{
			closeDialog();
		}
	},
	error: function(status, message) {
		this.albumButton.removeClassName(Buy.state.processing);
    Album.tracks.each(function(track){
      track[this.format].element.removeClassName(Buy.state.processing);
    }.bind(this));
		Buy.error(this, status, message);
  }
};

var newBuyObjects = {
  logged: {
    mp3: null,
    wma: null,
    gift: null,
    album: {
      mp3: null,
      wma: null,
      gift: null
    }
  }, 
  notlogged: {wma: null}
};

var afterLoginBuyItem = {};
var afterLoginCallBack = Prototype.K;
function clickListener(event){
  var element = $(event.target);
  if(element.hasClassName("lyrics")){element.target = "_blank"; return true;}
  if(!(element.hasClassName("buy") || element.hasClassName("track"))){return true;}
  var trackElement = element.up("span");
  var trackContainer = trackElement.up("dt");
  var trackId = trackContainer.trackId; //id.replace("track", "");
  var format = trackContainer.up("dl").className;
  var track = Album.tracks.detect(function(item){
    return item.id == trackId;  
  });  
  if(format == "wma" && newBuyObjects.logged[format].neverAsk && !trackContainer.hasClassName("karma")){return true;}
  Event.stop(event);
	if(format == "wma" && !trackContainer.hasClassName("karma")){ 
		try {
			newBuyObjects.notlogged[format].requestTrack(track);
		}catch(e){};
		return true;
	}
  if (!User.logged) {
    afterLoginBuyItem = {trackId: track.id, format: format};
    headerSignIn.call({message: "Please login to buy this track", success: buyAfterLogin});
  }else{
    try {newBuyObjects.logged[format].requestTrack(track);}catch(e){};
  }
}
function albumClickListener(event){
  event.stop();
  event.target.blur();
  var format = $("buy-album").className;
  
  if (!User.logged && format != "wma") {
    afterLoginBuyItem = {format: format};
    headerSignIn.call({message: "You need login to buy this album", success: buyAlbumAfterLogin});
  }else{
		try {newBuyObjects.logged.album[format].requestAlbum();}catch(e){};
	}
}
function buyAfterLogin(response){
  updatePage(response);
	var track = Album.tracks.detect(function(track){return track.id == afterLoginBuyItem.trackId;});
  newBuyObjects.logged[afterLoginBuyItem.format].requestTrack(track);
}
function buyAlbumAfterLogin(response){
  updatePage(response);
	newBuyObjects.logged.album[afterLoginBuyItem.format].requestAlbum();
}
