Review = {
    init: function(){
        $('div.review li.comments a').click(Review.showComments);
        //         $('div.review li.more_by a').hoverIntent({
        //  interval: 200,
        //  over: Review.showMoreBy,
        //  out: function(){
        //      // do nothing - click X to close
        //  }
        // }).click(function(){return false});
    	$('#tiny_review a:not(".disabled"), #full_review a:not(".disabled")').click(Review.newReview);
        //$('#sort_filters select').sexyCombo({triggerSelected:true});
        $('#action_links li').mouseenter(Review.doActionLinkEnter);
        $('#action_links').mouseleave(Review.doActionLinkLeave);
    },
    doActionLinkEnter: function(){
      switch (this.id) {
          case "follow_album" : 
            $('#action_links')
                .addClass("hover1")
                .removeClass("hover2")
                .removeClass("hover3");
            break;
          case "favorite_album"   : 
            $('#action_links')
                .removeClass("hover1")
                .addClass("hover2")
                .removeClass("hover3"); 
            break;
          case "recommend_album": 
            $('#action_links')
                .removeClass("hover1")
                .removeClass("hover2")
                .addClass("hover3");
      }  
    },
    doActionLinkLeave: function(){
        $('#action_links').attr("class", "");
    },
    newReview: function(){
        if (logged_in)
            showFacebox(this.href);
        else
            $(this).overlay({});
      return false;  
    },
    showComments: function(){
        var id = Review.getId(this)
        var comments = $('#comments_' + id);
        // if the comments are visible, then do nothing
        if (comments.is(":visible")) return false;
        if (comments.html().length > 0) {
            comments.show();
            return false;
        }
        // add the comments container elm
        $.get('/comments', {type: 'review', id: id}, function(data){
            // load the comments into the elm
            $('#comments_' + id)
                .html(data)
                .show()
                .children("a.hide")
                .click(Review.hideComments);
        });
        return false;
    },
    hideComments: function(){
        // hide the comments by sliding up and removing
        $('#comments_' + Review.getId(this)).hide();
        return false;
    },
    getId: function(obj){
        return $(obj).parents("div.review").attr("id").replace("review_", "")
    },
    showMoreBy : function(){
        var url = this.href;
        // get the position at which to show the facebox
        var offset = $(this).offset();
        $.extend($.facebox.settings, {
            top: Math.round(offset.top) - 260,
            left: Math.round(offset.left) - 200,
            width: 550,
            height:220,
            overlay: false
        });
        // tell the facebox to add caret to facebox html (make sure that close removes the caret)
        // put it after div.popup
    	$.facebox(function(){
    		$.get(url, function(data){
    			$.facebox(data);
    			var images = $('#imageflow img')
    			if (images.size() > 1) {
                	var image_flow = new ImageFlow();
                    image_flow.init({   ImageFlowID: "imageflow", 
                                        aspectRatio: 1.33, 
                                        xStep: 70, 
                                        percentLandscape: 100, 
                                        percentOther: 100, 
                                        imageFocusMax: 3,
                                        imageFocusM: 1.1,
                                        imagesHeight: 1.1,
                                        imagesM: 1.5,
                                        opacity:true,
                                        reflections: false, 
                                        reflectionP: 0.0,
                                        captions: false,
                                        preloadImages: false,
                                        startID: Math.round(images.size() / 2) });
    			}
    		});
    	});
        return false;
    },
    active_request: {},
    flag: function(story_id, action, obj) {
	  if (logged_in) {
      	var url = "/votes/?what=Review&id=" + story_id + "&a=show"
		$.facebox.settings.width = 370;
		$.facebox.settings.height = 235;
		showFacebox(url);
	  }
		return false;
	},
	pop: function(story_id, action, obj, what) {
	  if (!logged_in) {
	    $(obj).overlay({});
	  } else {
  	      var item = jQuery(obj).parents('li.vote');
 	      if (story_id > 0 && !item.hasClass("popped")) {
              // item.addClass('voted').children('div.buttons').fadeOutAndRemove();
		      Review.do_request(Review.get_params(1, story_id, action, what));	      		  
  	      }
	    }
		return false;
	},
	drop: function(story_id, action, obj, what) {
	  if (!logged_in) {
  	    $(obj).overlay({});
	  } else {
  	      var item = jQuery(obj).parents('li.vote');
  		if (story_id > 0) {
          // item.addClass('voted');
  		  item.children("div.buttons").fadeOutAndRemove();
			  Review.do_request(Review.get_params(2, story_id, action, what));
		  }
		}
		return false;
	},
	get_params: function(vote_type, story_id, action, what) {
		return { 	authenticity_token: jQuery('input[name="authenticity_token"]').val(), 
			       	id: story_id,
					what: what,
					vote_type: vote_type,
					a: action
				};
	},
	do_request: function(params, story_id, action) {
	    if (Review.active_request[params.id])
	        return false;
	    Review.active_request[params.id] = true;
	    jQuery.post("/votes/reviews", params, function(data){
			eval(data);
		});
	},
	flag_submit: function(){
		if (jQuery('#flag_form input:checked').size() == 0)
			return false;
		var params = { 	authenticity_token: jQuery('#flag_form input[name="authenticity_token"]').val(), 
			       		id: jQuery('#flag_form input[name="id"]').val(),
						what: "Review",
						a: jQuery('#flag_form input[name="a"]').val(),
						vote_type: jQuery('#flag_form input[name="vote_type"]:checked').val(),
						message: jQuery('#flag_form #message').val()
				};
		Review.do_request(params);
		return false;
	}
	
}

AlbumForm = {
    init: function(){
        $('#album_art_lookup').click(AlbumForm.doArtLookup);
        
    },
	doArtLookup : function(){
        var album =  $('#album_name').val(),
			artist = $('#album_artist_name').val()
		this.href = "http://images.google.com/images?q=" + encodeURIComponent((artist + " " + album).replace(/\s/g, "+")) + "&oe=utf-8&rls=org.mozilla:en-US:official&client=firefox-a&um=1&ie=UTF-8&sa=N&hl=en&tab=wi";
	}
}

ReviewForm = {
    init: function(){
        $('#review_body_tiny')
            .charCounter(140, {insert: "before", format: "%1", cutOffAt: 200})
            .charCounter(121, {
				insert: "before",
                format:"%1 twitter safe", 
                classname: "tweetcounter", 
                allowNegative: true
            });
    	$('#review_body_full').charCounter(3000, {
			insert: "before",
			format: "%1", 
			minimum: 400
		});
    	$('#submit_full').click(function(){
    	    $('input[name="tiny"]').attr("disabled", "disabled");
    		$('input[name="full"]').removeAttr("disabled");
    	});
    }
}

AlbumSearch = {
    form: null,
    details: null,
    album_timer: null,
    album_field: null,
    artist_field: null,
    old_artist: null,
    old_album: null,
    results : {},
    init : function(){

		$('#selected_album').bind("submit", function(){
			$('#genres select:first').removeAttr("disabled");
			var genres = 0;
			$('#genres select').each(function(){
				if ($(this).val() != "") genres++;
			});
			if (genres == 0) {
				alert("Please select at least one genre.");
				return false;
			}
		})

        AlbumSearch.artist_field = $('#artist');
        AlbumSearch.album_field = $('#album');
        AlbumSearch.form = $('#album_search_form form');
        AlbumSearch.form.bind("submit", AlbumSearch.doAlbumLookup);
        AlbumSearch.details = $('#album_details');
        
        // AlbumSearch.album_timer = setInterval("AlbumSearch.doAlbumLookup()", 1000)
        // $('#album_artist_name, #album_name').keypress(function(){
        //     clearTimeout(AlbumSearch.album_timer);
        //     AlbumSearch.album_timer = setTimeout("AlbumSearch.doAlbumLookup()", 1000);
        // }).change(AlbumSearch.doAlbumLookup);
        
        $('a.new_album_search').click(AlbumSearch.startOver);
        $('a.new_album_link').live('click', AlbumSearch.newAlbumForm);

        AlbumSearch.album_selector = $('#album_selector');
        $('#album_selector li').live('click', AlbumSearch.selectAlbum);
		$('#artist').focus();
		
		// if you've come here from the reviews home page search for something, then the "showpopr review query" (sprq) contains the
		// search term
		sprq = (typeof(sprq) != "undefined") ? sprq : null;

        if (sprq || $('#artist').val() || $('#album').val())
            AlbumSearch.doAlbumLookup();
        if ($('#artwork_image img').size() == 0 && $('#album_artwork_url').val()) {
            $('#artwork_image').append("<img src=\"" + $('#album_artwork_url').val() + "\" />");
        }

        // we should disallow submit of itunes album without choosing genres
        
    },
    startOver: function(){
      $('#album_selected').hide();
      $('#select_an_album').show();
      $('#album_details').hide();
      $('#selected_album').reset(); 
      $('#page_title').html("Step 1. Lookup Artist or Album");
      $('#album_search_form').show();
		$('#genres select:first').removeAttr("disabled");
      return false; 
    },
    // newAlbumUrl: function(url) {
    //     return url + "?artist_name=" + encodeURIComponent(AlbumSearch.artist_field.val()) + "&album_name=" + encodeURIComponent(AlbumSearch.album_field.val());
    // },
    newAlbumForm: function(){
        // first check if the form is filled in
	    AlbumSearch.album_selector.html("<ul><li class='progress'></li></ul>");
        AlbumSearch.standardSubmit = true;
        AlbumSearch.form.attr("action", "/add_album").submit();
        return false;  
    },
    albumSelected: function(){
      return (AlbumSearch.artist_field.val() + AlbumSearch.album_field.val()).length > 0;  
    },
    toggleDetails: function(){
            $('#album_details').toggle();
            $('#album_instructions').toggle();
            return false;
    },
    // the lookup form does double duty to provide params for new album form
    // if standardSubmit is set to true, then it will submit to the new album form, thus providing
    // the album and artist names to the prefill without cluttering up the URL
    doAlbumLookup: function(){
        if (AlbumSearch.standardSubmit) return true;
        AlbumSearch.album =  AlbumSearch.album_field.val(),
	    AlbumSearch.artist = AlbumSearch.artist_field.val(); 
	    if (sprq || (AlbumSearch.old_artist != AlbumSearch.artist || AlbumSearch.old_album != AlbumSearch.album)) {
            AlbumSearch.results = {};
	        AlbumSearch.old_artist = AlbumSearch.artist;
	        AlbumSearch.old_album = AlbumSearch.album;
	        var q = sprq ? sprq : AlbumSearch.artist + " " + AlbumSearch.album;
	        if (q.length > 1) {
    		    AlbumSearch.album_selector.html("<ul><li class='progress'></li></ul>");
                $.getJSON("/albums/lookup?q=" + q, AlbumSearch.showLocalResults);  
	        }
	    }
	    return false;
    },
    convertToKey : function(string) {
      return string.toLowerCase().replace(/[^a-z0-9]/gi, "");
    },
    showLocalResults: function(results) {
        $("#album_selector").find("li.progress").remove();
        if (results.resultCount > 0) {
            var list = AlbumSearch.album_selector.find("ul");
            list.html("");
            $(results.results).each(function(){
                var key = AlbumSearch.convertToKey(this.artist_name + this.album_name);
                AlbumSearch.results[key] = this;
                var html = "<li id=\"" + key + "\">\n";
                html += "<img src=\"" + this.artwork_url + "\" />\n";
                html += "<div>\n";
                html += "<span class=\"album\">" + this.album_name + "</span>\n";
                html += "by <span class=\"artist\">" + this.artist_name + "</span>\n";
                html += "(<span class=\"year\">" + this.year + "</span>)\n";
                html += "</div>\n";
                html += "</li>\n";
                list.append(html);
            })
        }
        var album = AlbumSearch.album, artist = AlbumSearch.artist;
        // itunes album search
		if (sprq) {
        	$.getJSON("http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsSearch?callback=?&media=music&limit=20&entity=album&attribute=albumTerm&term=" + sprq, AlbumSearch.showLookupResults);
			sprq = null;
		} else if (album && !artist)
        	$.getJSON("http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsSearch?callback=?&media=music&limit=20&entity=album&attribute=albumTerm&term=" + album, AlbumSearch.showLookupResults);
        // itunes artist search
        else if (artist && !album)
			$.getJSON("http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsSearch?callback=?&media=music&limit=20&entity=album&attribute=artistTerm&term=" + artist, AlbumSearch.showLookupResults);
        else if (artist && album) 
			$.getJSON("http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsSearch?callback=?&media=music&limit=20&entity=album&term=" + artist + " " + album, AlbumSearch.showLookupResults);
    },
    showLookupResults: function(results) {
        var list = AlbumSearch.album_selector.find("ul");
        if (results.resultCount > 0) {
            $(results.results).each(function(){
                var key = AlbumSearch.convertToKey(this.artistName + this.collectionName);
                // for year and label let us use copyright
                if (!AlbumSearch.results[key]) {
                    AlbumSearch.results[key] = {
                        artist_name: this.artistName,
                        album_name : this.collectionName,
                        artwork_url: this.artworkUrl100.replace("100x100","170x170"),
                        type: "iTunes",
                        itunes_id: this.collectionId,
                        itunes_artist_id: this.artistId,
                        amg_id: this.amgArtistId,
                        itunes_collection_url: this.collectionViewUrl,
                        year: (this.releaseDate != null ? this.releaseDate.substring(0,4) : null),
                        label: this.copyright ? this.copyright.substring(5) : null,
                        genre: this.primaryGenreName,
						release_date: (this.releaseDate ? new Date(this.releaseDate.substring(0,10).replace(/-/gi, "/")) : null)
                    };
                    console.log(AlbumSearch.results[key]);
                    var html = "<li id=\"" + key + "\">\n";
                    html += "<img src=\"" + this.artworkUrl60 + "\" />\n";
                    html += "<div>\n";
                    html += "<span class=\"album\">" + this.collectionName + "</span>\n";
                    html += "by <span class=\"artist\">" + this.artistName + "</span>\n";
                    html += "(<span class=\"year\">" + AlbumSearch.results[key].year + "</span>)\n";
                    html += "</div>\n";
                    html += "</li>\n";
                    list.append(html);
                }
            });
            $('#select_an_album').show();
        } else {
            if (list.find("li").size() == 0) {
                AlbumSearch.album_selector.html("<p>Nothing found! Check your spelling and try again, or <a href=\"/add_album\" class=\"new_album_link\">enter a new album</a>.</p>");
                $('#right_col a.new_album_link').click(AlbumSearch.newAlbumForm);
            }
        }
        return false;
    },
    selectAlbum : function(){

		// http://xml-us.amznxslt.com/onca/xml?&callback=jsonp1239887444283&Service=AWSECommerceService&AWSAccessKeyId=0PGBCS7Y9Q61TZ2SN3R2&Operation=ItemSearch&SearchIndex=Music&Sort=psrank&ResponseGroup=Small%2COffers%2CItemAttributes%2CImages&Artist=&Title=&ContentType=text%2Fjavascript&Style=http%3A%2F%2Fempire86.com%2Famazon_json%2Ftest.xsl
		// loop through until we find exact match on the title
		
        var item = AlbumSearch.results[this.id], details = AlbumSearch.details;
        if (!item) return false;
        // clearInterval(AlbumSearch.album_timer);
      	$('#selected_album').reset(); 
		//details.find("dd").html("");
        $("li.selected").removeClass("selected");
		$('#genres select:first').removeAttr("disabled");
        $(this).addClass("selected");
        // fill in the details panel
        details.find("dl.artist_name dd").html(item.artist_name);
        details.find("dl.album_name dd").html(item.album_name);
        details.find("dl.year dd").html(item.year);
        details.show();

        //AlbumSearch.hideArtworkInputs();
        $('#select_an_album').hide();
        $('#album_selected').show();
        $('#page_title').html("Step 2. Select an Album");
        $('#album_search_form').hide();
        if (item.type == "iTunes") {
			// don't forget to clear out non itunes hidden inputs as they are added
            $('#album_name').val(item.album_name);
            $('#album_artist_name').val(item.artist_name);
            $('#album_year').val(item.year);
            $('#album_amg_id').val(item.amg_id);
            $('#album_itunes_collection_url').val(item.itunes_collection_url);
            $('#album_itunes_id').val(item.itunes_id);
            $('#album_itunes_artist_id').val(item.itunes_artist_id);
            $('#album_id').remove();
            $('#genres').show();
            $('#sp_genres').hide();
			// get the music label
            // $.getJSON("http://xml-us.amznxslt.com/onca/xml?&callback=?&Service=AWSECommerceService&AWSAccessKeyId=0PGBCS7Y9Q61TZ2SN3R2&Operation=ItemSearch&SearchIndex=Music&Sort=relevancerank&ResponseGroup=Small%2COffers%2CItemAttributes%2CImages&Artist=" + encodeURIComponent(item.artist_name) + "&Title=" + encodeURIComponent(item.album_name) + "&ContentType=text%2Fjavascript&Style=http%3A%2F%2Fempire86.com%2Famazon_json%2Ftest.xsl", function(data){
            $('#artwork_image').addClass('progress').html('');
            $.getJSON("/albums/amazon?artist=" + encodeURIComponent(item.artist_name) + '&album=' + encodeURIComponent(item.album_name), function(data){
				var match = null;
				if (data.result.length > 0) {
					$(data.result).each(function(){
						// check for equality of release date!
						if (item.album_name == this.title.replace(" (2CDs)", "")) {
							match = this;
						}
						
					});
					if (!match) {
						match = data.result[0];
					}
				} 
				if (match) {
					item.label = match.label;
					item.asin = match.asin;
					if (match.image.large && parseInt(match.image.large.width) > 170) {
						item.artwork_url = match.image.large.src
                        // $('#artwork_provider').html('Amazon (' + match.image.large.width + ' x ' + match.image.large.height + ')');
                        // $('#artwork_original').html('<img src="' + item.artwork_url + '" />');
					} else {
                        // $('#artwork_provider').html('No match from Amazon, using iTunes image.');
                        // $('#artwork_original').html('<img src="' + item.artwork_url + '" />');
					}
				} else {
                    // $('#artwork_provider').html('No match from Amazon, using iTunes image.');
                    // $('#artwork_original').html('<img src="' + item.artwork_url + '" />');
					
				}
	        	details.find("dl.label dd").html(item.label);
	            $('#album_artwork_url').val(item.artwork_url);
	            $('#artwork_image').removeClass('progress').html("<img src=\"" + item.artwork_url + "\" />");
	            $('#album_label').val(item.label);
				$('#album_amazon_id').val(item.asin);
			})
            try {
                var genre = null;
				$('#genres select:first option').each(function(){
					if ($(this).html() == item.genre) {
						genre = this.value;
					}
				});
                if (genre) {
                    $('#genres select:first').val(genre).attr('disabled','disabled');
                }
            } catch(e) {}
        } else if (item.type == "showpopr") {
            var id = $('#album_id');
            if (id.size() == 0) {
                $('#hidden_info').append("<input type=\"hidden\" name=\"album_id\" id=\"album_id\" value=\"" + item.id + "\" />");
            } else {
                id.val(item.id);
            }
            $('#artwork_image').html("<img src=\"" + item.artwork_url.replace("_tile.", ".") + "\" />");
            $('#genres').hide();
            $('#sp_genres').html("<dl><dt>Genres</dt><dd>" + item.topics.join("/") + "</dd></dl>").show();
	        details.find("dl.label dd").html(item.label);
            
            if (item.topics[0]) 
                $('#album_topics').val(item.topics[0]);
            if (item.topics[1])
                $('#album_topic_ids_1').val(item.topics[1]);
            if (item.topics[2])
                $('#album_topic_ids_2').val(item.topics[2]);
            console.log('Processed showpopr album.')
        }
        return false;
    }

}