var FullSizeImage = Class.create();
FullSizeImage.prototype = {
  initialize: function(image, imageCopy, bigImageSrc) {
    var img = new Image();
    img.src = bigImageSrc;
    this.image = $(image);
    this.imageCopy = $(imageCopy);
    this.container = this.imageCopy.up("div");
    this.bigImageSrc = bigImageSrc;
    this.inFullSize = false;
		this.effectRunning = false;
    this.fullSizeLoaded = false; 
		this.image.up("a").observe("click", this.showFullSize.bindAsEventListener(this), false);
		this.imageCopy.next("div").down("a.close").observe("click", this.hideBigPicture.bindAsEventListener(this), false);
		this.imageCopy.observe("click", this.hideBigPicture.bindAsEventListener(this), false);
    Event.observe(document, 'keypress', this.checkKeyPress.bindAsEventListener(this), false);
  },
  checkKeyPress:function(event_object){
  	var key = event_object.keyCode || event_object.which;
		if(key == 27){
			Event.stop(event_object);
    	if(this.inFullSize){
      	this.hideBigPicture();
    	}
		}
  },
  hideBigPicture: function(event){
		if(event){Event.stop(event);}
		if(this.effectRunning){return false;}
		this.effectRunning = true;
		this.imageCopy.next("div").hide();
    new Effect.Parallel(
      [ new Effect.Scale(this.imageCopy, 33.33, { sync: true, transition: Effect.Transitions.sinoidal, restoreAfterFinish: false}),
        new Effect.Scale(this.container, 33.33, { sync: true, transition: Effect.Transitions.sinoidal, restoreAfterFinish: false})
      ], {duration: 0.8, afterFinish: function(){
													this.image.setOpacity(1);
													this.image.next("span").show();
													this.imageCopy.hide();
													this.imageCopy.style.width = "200px";
													this.imageCopy.style.height = "200px";
													this.imageCopy.next("div").hide();
													this.container.hide();
													this.container.style.width = "200px";
													this.container.style.height = "200px";
													this.inFullSize = false;
													this.effectRunning = false;
													var el = this.image.up("a");
													if(el.tooltip && el.tooltip.mousemove.activate){el.tooltip.mousemove.activate();}
													}.bind(this)
		});  
  },
  showFullSize: function(event){
    Event.stop(event);
		this.image.blur();
		if(this.inFullSize || this.effectRunning){return false;}
		var el = this.image.up("a");
		if(el.tooltip && el.tooltip.mousemove.currentlyVisible && el.tooltip.mousemove.deactivate){el.tooltip.mousemove.deactivate();}
			this.effectRunning = true;
			this.image.next("span").hide();
        this.imageCopy.src = this.bigImageSrc;
				new Effect.Fade(this.image, {to: 0.2, duration: 0.5, afterFinish: function(){
        this.container.show();
        new Effect.Parallel(
          [ new Effect.Appear(this.imageCopy, { sync: true, from: 0.2 }),
            new Effect.Scale(this.imageCopy, 300, { scaleMode: { originalHeight: 200, originalWidth: 200 }, sync: true, transition: Effect.Transitions.sinoidal, restoreAfterFinish: false}),
            new Effect.Scale(this.container, 300, { scaleMode: { originalHeight: 200, originalWidth: 200 }, sync: true, transition: Effect.Transitions.sinoidal, restoreAfterFinish: false})
          ], {duration: 1.5, afterFinish: function(){
														this.imageCopy.next("div").show(); 
														this.inFullSize = true; 
														this.effectRunning = false;
														this.imageCopy.style.width = "600px";
														this.imageCopy.style.height = "600px";
														this.container.style.width = "600px";
														this.container.style.height = "600px";
														}.bind(this)});  
        }.bind(this)});  
  }
};
var Album = {
	init: function (sku) {
		if(!(sku && $(sku))){ return false; }
		this.sku = sku;
		this.container = $(sku);
		this.title = $("albumTitle").firstChild.nodeValue.strip();
		this.artist = $("albumTitle").getElementsByTagName("a")[0].innerHTML.strip();
		this.price = {mp3: '8.88', wma: '7.77'};
		this.trackprice = {mp3: '0.88', wma: '0.77'};
		this.tracks = this.getTracks();
	},
	getTracks: function () {
		var tracks = [];
		$$("#content .container .only dl dt span.sample").each(function(element, index){
			var trackContainer = element.up("dt");
			if(!(trackContainer)){ return false; }
			var trackId = this.getTrackId(trackContainer);
			if(trackId === null){ return false; }
			trackContainer.trackId = trackId;
			var trackObj = {container: trackContainer, id: trackId, number: index+1};
			tracks.push(trackObj);
		}.bind(this));
		return tracks;
	},
	getTrackId: function(element){
		if(element && element.id){
			var regexpResult = /track(.+)$/.exec(element.id);
			if(regexpResult && regexpResult.length && regexpResult[1]){
				return regexpResult[1];
			}
		}
		return null;
	}
};
var Buy = {
	dialogs : ["buy-mp3", "buy-album-mp3", "request-processing-message", "error-message", "buy-wma", 
		"insufficient-balance-message", "download-track-message", "download-album-message", "buy-album-wma",
		"buy-album-wma-link-on-email", "album-only-mp3", "album-only-wma", "novice-message"],
	state : { bought : "bought", processing : "processing", albumOnly : "album-only" },
	novice : false,
	noviceNotified : false,
	albumButton : {},
	neverAsk : {},
	url : {
		buyTrack : "/mpeg/buytrack",
		giftTrack : "/gift/make",
		albumState : "/album/present/",
		buyAlbum : "/mpeg/buyalbum?sku=",
		novice : "/user/upgrade_newbie"
		},
	initTracks: function(format){
		Album.tracks.each(function(track){
			track[format] = {};
			track[format].element = track.container.down("span."+format); 
			track[format].title = track[format].element.down("a.track").innerHTML.strip();
			track[format].url = track[format].element.down("a.track").href; 
		});
	},	
  updateTrack: function (track, format, state){
		track[format].element.addClassName(state);
  },
	isNovice: function(){
		if(this.novice && !this.noviceNotified && $(this.dialogs[12])){
			showMessage($(this.dialogs[12]).innerHTML);
			this.noviceWarning();
			this.noviceNotified = true;
			return true;
		}else {return false;}
	},
	noviceWarning: function(){
		new Ajax.Request(this.url.novice);
	},
	karmaBalanceIndicator: $("karmaBalance"),
	accountBalanceIndicator: $("accountBalance"),
	updateBalance: function(response){
		if("karma" in response && this.karmaBalanceIndicator){
			this.karmaBalanceIndicator.up("dt").style.display = !parseFloat(response.karma) ? "none" : "block";
			this.karmaBalanceIndicator.update(response.karma);
		}
		if("balance" in response && this.accountBalanceIndicator){
			this.accountBalanceIndicator.up("dt").style.display = !parseFloat(response.balance) ? "none" : "block";
			this.accountBalanceIndicator.update("$"+response.balance);
		}
	},
	error: function(obj, status, message){
		var messageHTML;
		switch(status){
		case '401':
			if( $("error-401-message") ){
				showMessage($("error-401-message").innerHTML);
			}
			return true;
		case '402':
      if( obj.scenario.insufficientBalance && $(obj.scenario.insufficientBalance) ){
				showMessage($(obj.scenario.insufficientBalance).innerHTML);
			}
			return true;
		case '404':
			if( $("contact-support-message") && $("error-404-message")){
				$("error-404-message").down("span.subject").innerHTML = obj.albumButton ? "album" : "track";
				$("contact-support-message-content").innerHTML = $("error-404-message").innerHTML;
				showMessage($("contact-support-message").innerHTML);
			}
			return true;
		case '408':
      showMessage($(obj.scenario.emailError).innerHTML.interpolate({email: obj.giftEmail}));
			return true;
		default:
			if( $("error-message") && $("error-default-message")){
        $("error-message-content").innerHTML = message || $("error-default-message").innerHTML;
				showMessage($("error-message").innerHTML);
			}
			break;
		}
	}
};

Faves = {
	init: function (){
    this.container = $("content").down("div.fave");
    this.heart = this.container.down("a.heart");
		this.heart.observe("click", function(event){ event.stop(); this.toggle(); }.bindAsEventListener(this));
	},
	toggle: function (){
  	if($A(Effect.Queues.get(this.container.id)).length){
			return false;
		}
  	new Effect.Puff(this.heart, {
  		queue: {position:'end', scope: this.container.id, limit:1},
  		duration: 0.5, 
  		afterFinish: function(){
				var k = 0;
				if(!this.heart.hasClassName('active')){
					this.heart.addClassName('active'); 
					k = 1;
				}else{
					this.heart.removeClassName('active');
					k = -1;
				}
				this._updateBalance(k);
				this.heart.show();
			}.bind(this)});
  	  new Ajax.Request('/album/favetoggle/'+this.container.id.replace(/fave/, ''), { 
  		  onFailure: function(){
  			//Action on error with faving album
  		  }});	
	},
	_updateBalance: function(k){
		var amountContainer = this.container.down("span.amount");
		var oldNumber = parseInt(amountContainer.innerHTML);
		var newNumber = oldNumber + k;
		amountContainer.style.display = (newNumber==0) ? "none" : "block";
		var text = (newNumber!=1) ? "faves" : "fave";
		amountContainer.update(newNumber+" "+text);
	}
};

function updatePage(response){
    if(response.novice){Buy.novice = true;}
    if(response.neverAsk){
      ["mp3", "wma"].each(function(format){
        newBuyObjects.logged[format].neverAsk = response.neverAsk[format];
        newBuyObjects.logged[format].setScenario();
      });
    }
    if (response.dialogs) {
      try{$("loggedDialogs").update(response.dialogs);}catch(e){};
			}

    if (response.tabs) {
      try{Album.container.update(response.tabs);}catch(e){};
    }
    if (response.faves) {
      try{
        $("albuminfo").update(response.faves);
        Faves.init();
      }catch(e){};
    }
    if (response.header) {
      try{
      	Buy.karmaBalanceIndicator = $("karmaBalance");
      	Buy.accountBalanceIndicator = $("accountBalance");
      }catch(e){};
		}
    if (response.boughtAlbum) {
			$H(response.boughtAlbum).each(function(item){
        if(item.value){
          $("buy-album").down("a."+item.key).addClassName("bought");
	}
});
    }
    if (response.review) {
      try{$("comments").update(response.review);}catch(e){};
    }
    User.logged = true;
    User.ban.album.wma = null;
    Album.tracks = Album.getTracks();
    try{Buy.initTracks("wma");}catch(e){};
    try{Buy.initTracks("mp3");}catch(e){};
    try{Buy.initTracks("gift");}catch(e){};
    ppfmPlayer.addPlaylist(Album.sku);
}

Event.observe(window, "load", function(){
  if(!headerSignIn){headerSignIn = new InstanLogin();}
  headerSignIn.defaultOptions.success = function(response){updatePage(response); closeDialog();}.bind(headerSignIn);
  $("blockmp3").stopObserving("click", emptyClickListener);
  $(Album.sku).observe("click", clickListener.bindAsEventListener(), false);
  $("buy-album").observe("click", albumClickListener.bindAsEventListener(), false);
  var review = $("comments") ? $("comments").down("h2 a") : null;
  if(review){
    review.observe("click", function(event){
      event.stop();
      if (!User.logged) {
        var onsuccess = headerSignIn.defaultOptions.success;
        headerSignIn.call({success: function(response){onsuccess(response); $("comments").scrollTo(); }});
      }    
    }.bindAsEventListener());
  }
  var heart = $("content").down("div.album div.heart");
  if(heart){ 
    heart.observe("click", function(event){
      event.stop();
      if (!User.logged) {
        var onsuccess = headerSignIn.defaultOptions.success;
        headerSignIn.call({success: function(response){
          onsuccess(response); 
          if(!Faves.heart.hasClassName("active")){Faves.toggle();} 
        }});
      }    
    }.bindAsEventListener());
  }
}, false);
