HEARST.ff.detail = {
    
    init: function() {    
    
        if( HEARST.utils.getQueryVariable('ur_login_failed')) HEARST.ff.detail.saveFragrance();
        
        // Bind show all reviews handler
        $('#read_all a').bind('click', function(){ HEARST.ff.detail.readAll( $(this) ); });    
        // Bind handler for ratings
        $('#form_container ul.rating li').bind('mouseover', function(){ HEARST.ff.detail.rate( $(this) ); });
        // Bind handler for clearing ratings
        $('#form_container p.rating').bind('mouseover', function(){ HEARST.ff.detail.clearRating(); });
        // Bind handler for save action
        $('ul a.save').bind('click', function(){ HEARST.ff.detail.saveFragrance(); });
        $('ul a.edit').bind('click', function(){ HEARST.ff.detail.editFragrance(); });
        
        HEARST.ff.detail.getRecos();
        HEARST.ff.getComments('init');
        HEARST.ff.detail.showCommentForm();
        
        $('p.username').text(mag_user.user_name);
        
        $('#form_container button').bind('click', function(){ HEARST.ff.postComment(); });            
        $('#ff_message button').bind('click', function(){ $('#ff_message').fadeOut('fast'); });
        $('#btn_google_shopping').bind('click', function(){ window.open( ("http://www.google.com/products?q=" + $('#google_shopping').val() + "&hl=en"), "google_shopping" ) });

		$("#google_shopping").keyup(function(e) {
			if(e.keyCode == 13) {window.open( ("http://www.google.com/products?q=" + $('#google_shopping').val() + "&hl=en"), "google_shopping" )}
		}); 

        // Set edit profile actions
        //( mag_user.ur_id ) ? $('a.edit').bind('click', function(){ window.location = "/registration/"; }) : $('a.edit').bind('click', function(){ HEARST.tempUtils.writeCookie( "ff_action", "edit_profile", 1 ); window.location = "/login/"; });
        //( mag_user.ur_id ) ? $('a.edit').bind('click', function(){ window.location = "/registration/"; }) : $('a.edit').bind('click', function(){ window.location = "/login/"; });
        
        // Check for action cookie
        if( HEARST.tempUtils.readCookie("ff_action") == "save_fragrance" ) {
            HEARST.ff.detail.saveFragrance();
            HEARST.tempUtils.eatCookie("ff_action");
        }
		if( HEARST.tempUtils.readCookie("ff_action") == "edit_fragrance" ) {
            HEARST.ff.detail.editFragrance();
        }

		// Set login cookies
        $('a.sign_in_ff').bind("click.login_click", function(){
            // Set next url cookie
            if ( (document.location.href.indexOf('registration') == -1) && (document.location.href.indexOf('login') == -1) ) {
                var _nexturl = document.location.href;
            } else {
                var _nexturl = "http://" + document.domain;
            }
            
            HEARST.tempUtils.writeCookie('nexturl', _nexturl, 1);
            window.location = "/registration/";
            
        });
		
		// Show or hide the edit profile link
//		( mag_user.ur_id ) ? $('ul.ff_tools a.edit').show() : $('ul.ff_tools a.edit').remove();

    },
    
    readAll: function( show_link ) {
        // Toggle all reviews (except top rated)
        $('div.review:not(div.review.top_review)').slideToggle('fast');
        // Change link text
        ( escape( $(show_link).text() ) == "Read%20all%20Reviews%20%BB") ? $(show_link).text( unescape( "Read%20less%20Reviews%20%BB" ) ) : $(show_link).text( unescape( "Read%20all%20Reviews%20%BB" ) );
        
    },
    
    rate: function( rating ) {

        $(rating).attr('class','on');
        $(rating).prevAll().attr('class','on');
        $(rating).nextAll().attr('class','off');
    
    },
    
    clearRating: function() { $('#form_container ul.rating li').attr('class','off'); },
    
    getRecos: function() {
        
        var $readerRatings = $('#ff_fragrance_info .rating, #reviews_hdr ul.rating');
        
        $.ajax({
            type: 'GET',            
            url: '/api/js/Fragrance/' + HEARST.site.article.id,
            dataType: 'json',                
            error: function( x ){
                // Error message
            },
            success: function( data ){
                
                var _recos = [],
                    _for = "Female", // Default to female
                    _gender = data.fragrance.gender.anon,
                    _rating = Math.round(data.rate);
                    
                // Set rating of artcle
                if (_rating) {
                    $readerRatings.find('li:lt(' + _rating + ')').attr('class','on');
                }
                
                ( HEARST.utils.getQueryVariable("for") ) ? _for = HEARST.utils.getQueryVariable("for") : _for = data.fragrance.gender.anon;
                
				if( HEARST.site.prefix == "seventeen" ) {
					
					if( _for = "Unisex" ) _for = "Girl";
					
					$(data.tags).each(function(i, val){ // If it's for male or female, prepend to array, else append.
						var _id = val.tag.split(":");                    
						if( ( _for == "Girl" ) && ( _id[0].indexOf("F_") != -1 ) ) {
							_recos.unshift( _id[2] );    
						} else if( ( _for == "Boy" ) && ( _id[0].indexOf("M_") != -1 ) ) {
							_recos.unshift( _id[2] );
						} else {
							_recos.push(_id[2]);
						}
					});
					
				} else {
				
					if( _for = "Unisex" ) _for = "Woman";
					
					$(data.tags).each(function(i, val){ // If it's for male or female, prepend to array, else append.
						var _id = val.tag.split(":");                    
						if( ( _for == "Woman" ) && ( _id[0].indexOf("F_") != -1 ) ) {
							_recos.unshift( _id[2] );    
						} else if( ( _for == "Man" ) && ( _id[0].indexOf("M_") != -1 ) ) {
							_recos.unshift( _id[2] );
						} else {
							_recos.push(_id[2]);
						}
					});
					
				}

                $(_recos).each(function(i, val){
                                        
                    var rating, $rating, $recommendation, $stars;
    
                    $.ajax({
                        type: 'GET',            
                        url: '/api/js/Fragrance/' + val,
                        dataType: 'json',                
                        error: function( x ){
                            // Error message
                        },
                        success: function( data ){
                        
                            // Build Recommendation string
                            var reco_string = "<h2><a href='" + data.url_name + "'>" + data.title + "</a></h2>";
                            reco_string += "<p class='house'>" + data.fragrance.house + "</p>";
                            reco_string += "<p class='rating'>Reader Rating</p><ul class='rating'><li class='off'><li class='off'><li class='off'><li class='off'><li class='off'></li></ul>";              
                            reco_string += "<a href='" + data.url_name + "'><img src='" + data.main_image.small_url + "' width='120' height='120' /></a>";
                            reco_string += "<p class='bite'>" + data.fragrance.salesbite + "</p>";
                            reco_string += "<a href='" + data.url_name + "' class='go'></a>";

                            $recommendation = $(reco_string);
                            rating = Math.round(data.rate);

                            if (rating) {
                                $stars = $($recommendation[3]);
                                
                                $stars.find('li:lt(' + rating + ')')
                                        .attr('class','on');
                            }

                            $('.recommendation:eq(' + i + ')').append($recommendation);
                            
                        }
                        
                    });    
                    
                });
                
            }
            
        });
        
    },
    
    showCommentForm: function() {
        
        if( mag_user.ur_id ) {
			$('#comment_hdr_logged_in').show();    
			$('#form_container').show();
        } else {
			$('#comment_hdr_logged_out').show();    
			$('#form_container_login').show();
        }
        
    },
    
    verifyForm: function( form ) {
        if( (form.user_name.value == "") || (form.password.value == "") ) {
            alert("Please fill out your username and password before submitting.");
            return false;
        } else {
            return true;    
        }
        
    },
    
    loginFailText: function() {
		if( HEARST.utils.getQueryVariable('ur_login_failed')){
			var urloginfailed = unescape(HEARST.utils.getQueryVariable('ur_login_failed'));
			var errortext = "";
			if( urloginfailed == "missing username.") {
				errortext = "You did not provide a username.";
			}
			if( urloginfailed == "invalid user name.") {
				errortext = "We could not locate an account with that username.";
			}
			if( urloginfailed == "invalid email.") {
				errortext = "We could not locate an account with that email address.";
			}
			if( urloginfailed == "missing password.") {
				errortext = "You did not provide a password.";
			}
			if( urloginfailed == "invalid password for user name.") {
				errortext = "The password is not correct for that username.";
			}
			if( urloginfailed == "invalid password for email.") {
				errortext = "The password is not correct for that email address.";
			}
			$('#ff_sign_in h6 span').text(errortext + ' Please try again.');    
        }

	},
	
    saveFragrance: function() {
		HEARST.ff.detail.loginFailText();		
        if( mag_user.ur_id ) {
            
            $.ajax({
                type: 'GET',
                url: '/api/js/FragranceBook?cachebust=' + HEARST.ff._cacheBust,
                dataType: 'json',
                error: function(x){
                    // If no Fragrance book is found, create one.
                    if( x.status == 404 ) {                
                        $.ajax({
                             type: 'POST',   
                             url: '/api/js/FragranceCategory',
                             data: 'title=Your Fragrance File',
                             dataType: 'json',
                             error: function(x){     
                                //
                             },
                             success: function(data){   
                                HEARST.ff.detail.saveFragrance();                    
                             }
                        });                    
                    }
                },
                success: function( frag ) {
                    
                    $.ajax({
                        type: 'POST',
                        url: '/api/js/FragranceBook/' + frag[0].id + '?cachebust=' + HEARST.ff._cacheBust,
                        dataType: 'json',
                        data: 'fragrance_id=' + HEARST.site.article.id + '&_method=PUT',
                        error: function(x){
                            if(x.status == 200) $('#ff_message').fadeIn('fast');
                            if(x.status == 409) {
                                $('#ff_message').empty();
                                $('#ff_message').html('<button class="close"><span>close</span></button><p style="font-size:11px;">You have already saved this fragrance to your <a href="/fragrance-finder/fragrance-file/">Fragrance File &#187;</a></p>');
                                $('#ff_message').fadeIn('fast');
                                $('#ff_message button').bind('click', function(){ $('#ff_message').fadeOut('fast'); });
                            }
                        },
                        success: function( frag ) {                        
                            
                            $('#ff_message').fadeIn('fast');
                            
                        }
                    
                    });                        
                    
                }
            });            
            
        } else {
			// Set action cookie
        	HEARST.tempUtils.writeCookie( "ff_action", "save_fragrance", 1 );
            $('#ff_sign_in').fadeIn('fast');    
        }
    
    },

    editFragrance: function() {
		HEARST.ff.detail.loginFailText();
        if( mag_user.ur_id ) {
			document.location.href = '/fragrance-finder/fragrance-file/';        
        } else {
			// Set action cookie
        	HEARST.tempUtils.writeCookie( "ff_action", "edit_fragrance", 1 );
            $('#ff_sign_in').fadeIn('fast');    
        }
    
    }

}
