var displayHiddenRating = function( crw )
{
    /*
    if( $('DIV.rate_container:hidden',crw).length )
    {
        $('DIV.rate_container:hidden:not(:last)',crw).each(function(i, elem)
        {
            elem.fadeIn(400).removeClass("hidden");
        });
    }
    */

    var hidden_rating_containers = $('DIV.rate_container:hidden',crw);

    if( hidden_rating_containers.length > 0 )
    {
        
        $('DIV.rate_container:hidden:first',crw).each(function(i, elem){
            if( i>0 ) $(this).fadeIn(400).removeClass("hidden");
        });
    }

}

$(document).ready(function()
{
    // firefox radiobutton fix
    if($.browser.mozilla) $("form.rate").attr("autocomplete", "off");

        $("div#makeMeScrollable").smoothDivScroll({
                autoScroll: "onstart" ,
                autoScrollDirection: "left",
                autoScrollStep: 1,
                autoScrollInterval: 15,
                startAtElementId: "startAtMe",
                visibleHotSpots: "always",
                startAtElementId: "airplanes"
        });

    $("A.results","SPAN.rating_tools").live("mouseover mouseout",function(event){
        if ( event.type == "mouseover" ) {
            $(this).addClass("hover");
        }
        else
        {
            $(this).removeClass("hover");
        }
    });

    $('form#search input').focus(function(){
        if($(this).val()==='Try for example iPad, #tablets or iPhone vs Nokia')
        {
            $(this).val("").removeClass("unactive");
        }
    });

    $('form#search input').blur(function(){
        if( $(this).val()==='' )
        {
            $(this).val('Try for example iPad, #tablets or iPhone vs Nokia').addClass("unactive");
        }
    });

/*
 *
 *EI FUTAA SUORAAN
    $("div#categories_box").smoothDivScroll({ 
        autoScroll: "onstart",
        autoScrollDirection: "backandforth",
        autoScrollStep: 1,
        autoScrollInterval: 15,
        startAtElementId: "cars",
        visibleHotSpots: "always"
    });
*/

    $("a.modal").fancybox();

    $('#ua_login').click(function(){
        $('#user').slideToggle();
        return false;
    });

    $('a.addNew.disabled').click(function(){
        $.ajax({
            type: "GET",
            url: mooxe.settings.controller+'/register/login-needed',
            success: function(data) {
                $.fancybox(data,{
                    'autoDimensions'            : false,
                    'width'                     : 450,
                    'height'        		: 'auto',
                    'transitionIn'		: 'none',
                    'transitionOut'		: 'none'
                });
            }
        });
        return false;
    });

    $('UL.children','DIV.category').jScrollPane();

    if($('#signin_username').length>0 )
    {
        var u_elem = $('#signin_username');
        if( u_elem.val()=="")
        {
            u_elem.val('Username');
        }
        u_elem.focus(function(){
            if(u_elem.val()=="Username")
            {
                u_elem.val('');
            }
        });
        u_elem.blur(function(){
            if(u_elem.val()=="")
            {
                u_elem.val('Username');
            }
        });
    }

    if($('#signin_password').length>0 )
    {
        var p_elem = $('#signin_password');
        if( p_elem.val()=="")
        {
            p_elem.val('Password');
        }
        p_elem.focus(function(){
            if(p_elem.val()=="Password")
            {
                p_elem.val('');
            }
        });
        p_elem.blur(function(){
            if(p_elem.val()=="")
            {
                p_elem.val('Password');
            }
        });
    }
    /**
     *
     * Rating
     *
     */
     $('IMG.r_rating','FORM.rate').live("click",function(){
        var crw = $(this).parents('DIV.c_r_w');

        _gaq.push(['_trackPageview', '/skip-rating']);

        var container = $(this).closest("DIV.rate_container");

        container.fadeOut(400, function(){
                container.delay(600).remove();
                // Show the last hidden one
                if( $('DIV.rate_container:hidden:last', crw).length > 0 )
                {
                    $('DIV.rate_container:hidden:last', crw).fadeIn(500).removeClass("hidden");

                }

        });

        var categoryId = "";

        var h3 = crw.prevAll("h3");

        if( h3.length>0 && h3.attr("id") )
        {
            categoryId = "/categoryId/"+h3.attr('id');
        }

        var h2 = crw.prevAll("h2.versus");

        if( h2.length>0 && h2.attr("id") )
        {
            categoryId = "/categoryId/"+h2.attr('id');
        }


        if( typeof( page ) != 'undefined' )
        {
            var page_id = "";

            var versus_terms = "";

            if( typeof( page.id ) != 'undefined' )
            {
                page_id = "/"+page.id;
            }

            if( typeof( page.versus1 ) != 'undefined' )
            {
                versus_terms = "/versus1/"+page.versus1+"/versus2/"+page.versus2;
            }

            $.ajax({
                url: mooxe.settings.controller+'/'+page.type+'/getNewRating'+page_id+categoryId+versus_terms,
                success: function(data) {
                    var newRating = $(data).hide();

                    crw.append( newRating );

                    displayHiddenRating( crw );
                }
            });
        }
     });

     $('INPUT.rateradio','FORM.rate').live("click", function()
     {
        var crw = $(this).closest('DIV.c_r_w');

        _gaq.push(['_trackPageview', '/rate-something']);

        var form = $(this).closest("FORM.rate");

        var container = form.parent("DIV.rate_container");

        container.addClass("changeRate").delay(600).slideToggle(500, function(){
            container.remove();
            if( $('DIV.rate_container:hidden:last',crw).length )
            {
                $('DIV.rate_container:hidden:last',crw).fadeIn(500).removeClass("hidden");
            }
        });

        $.ajax({
          type: "POST",
          url: form.attr("action"),
          data: form.serialize(),
          success: function() {
            container.animate({},3000,function(){
                if( typeof( page ) != 'undefined' )
                {
                    var h3 = crw.prevAll("h3");

                    var categoryId = "";

                    if( h3.length>0 && h3.attr("id") )
                    {
                        categoryId = "/categoryId/"+h3.attr('id');
                    }

                    var h2 = crw.prevAll("h2.versus");

                    if( h2.length>0 && h2.attr("id") )
                    {
                        categoryId = "/categoryId/"+h2.attr('id');
                    }

                    var page_id = "";

                    var versus_terms = "";

                    if( typeof( page.id ) != 'undefined' )
                    {
                        page_id = "/"+page.id;
                    }

                    if( typeof( page.versus1 ) != 'undefined' )
                    {
                        versus_terms = "/versus1/"+page.versus1+"/versus2/"+page.versus2;
                    }

                    $.ajax({
                      url: mooxe.settings.controller+'/'+page.type+'/getNewRating'+page_id+categoryId+versus_terms,
                      success: function(data) {
                        if( page.type == "category" )
                        {
                            updateMyProducts();
                        }

                        var newRating = $(data).hide();

                        crw.append( newRating );

                        displayHiddenRating( crw );

                      }
                    });
                }
                });
          }
        });

        return false;


     });

     $('INPUT.s_rating','FORM.rate').live("click",function(){
        var crw = $(this).parents('DIV.c_r_w');

        _gaq.push(['_trackPageview', '/rate-something']);

        var form = $(this).parents("FORM.rate");

        var container = form.parent("DIV.rate_container");

        $.ajax({
          type: "POST",
          url: form.attr("action"),
          data: form.serialize(),
          success: function() {
            container.fadeOut("slow",function(){
                if( typeof( page ) != 'undefined' )
                {

                    var h3 = crw.prevAll("h3");

                    var categoryId = "";

                    if( h3.length>0 && h3.attr("id") )
                    {
                        categoryId = "/categoryId/"+h3.attr('id');
                    }

                    var page_id = "";

                    var versus_terms = "";

                    if( typeof( page.id ) != 'undefined' )
                    {
                        page_id = "/"+page.id;
                    }

                    if( typeof( page.versus1 ) != 'undefined' )
                    {
                        versus_terms = "/versus1/"+page.versus1+"/versus2/"+page.versus2;
                    }

                    $.ajax({
                      url: mooxe.settings.controller+'/'+page.type+'/getNewRating/'+page_id+categoryId+versus_terms,
                      success: function(data) {

                          var newRating = $(data);

                          crw.append( newRating.fadeIn("normal") );

                      }
                    });
                }
                }).remove();
          }
        });
        
        return false;
     });

     $('INPUT.rateradio','FORM.rate').live("focus click",function()
     {
        $(this).siblings("div.bt_container").children("INPUT.s_rating").attr("disabled",false);
     });

     $("A.create_hot_pair","div.rate_container").live("click",function(){
        var elem = $(this);

        elem.text("Creating..");

        var form = elem.parent().prev("form");
        var product_1 = form.children("#my_rating_product1_id").val();
        var product_2 = form.children("#my_rating_product2_id").val();


        var url = $(this).attr("href");

        $.ajax({
          dataType: 'json',
          url: url+'/product_1/'+product_1+'/product_2/'+product_2,
          success: function(data) {

            if(data.status==false)
            {
                elem.effect("shake", { times:3 }, 150).text(data.message);
            }
            else if(data.status==true)
            {
                elem.text("Hot pair created!");
            }
          }
        });


        return false;
     });

    /*
     *
     * REGISTER
     *
     */
    $("#register-form").validate({
		rules: {
			'sf_guard_user[first_name]': "required",
			'sf_guard_user[last_name]': "required",
                        'sf_guard_user[captcha]' : "required",
			'sf_guard_user[password]': {
				required: true,
				minlength: 5
			},
			'sf_guard_user[password_confirmation]': {
				required: true,
				minlength: 5,
				equalTo: "#sf_guard_user_password"
			},
			'sf_guard_user[email_address]': {
                                required: true,
				email: true,
                                remote: {
                                    url: mooxe.settings.controller+"/validate/email",
                                    type: "post"
                                }
			},
			'sf_guard_user[t_and_c]': "required"
		},
		messages: {
			'sf_guard_user[first_name]': "Please enter your firstname",
			'sf_guard_user[last_name]': "Please enter your lastname",
                        'sf_guard_user[captcha]' : "Please enter characters from the box below",
			'sf_guard_user[password]': {
				required: "Please provide a password",
				minlength: "Your password must be at least 5 characters long"
			},
			'sf_guard_user[password_confirmation]': {
				required: "Please provide a password",
				minlength: "Your password must be at least 5 characters long",
				equalTo: "Please enter the same password as above"
			},
			'sf_guard_user[email_address]': {
                            required: "Please enter your email address",
                            email: "Please enter a valid email address",
                            remote: jQuery.format("{0}")
                        },
			'sf_guard_user[t_and_c]': "Please accept our terms & conditions"
		}
	});

    /*
     *
     * CONTACT
     *
     */
    $("#contact-form").validate({
		rules: {
			'contact[name]': "required",
			'contact[message]': "required",
			'contact[email]': {
                                required: true,
				email: true
			}		},
		messages: {
			'contact[name]': "Please enter your name",
			'contact[message]': "We'd really value your feedback..",
			'contact[email]': {
                            required: "Please enter your email address",
                            email: "Please enter a valid email address"
                        }
                }
	});

    /*
     *
     * PRODUCT
     *
     */
    $("#add-product-form").validate({
		rules: {
			'product[name]': {
                                required: true,
                                remote: {
                                    url: mooxe.settings.controller+"/validate/product",
                                    type: "post"
                                }
			}
		},
		messages: {

			'product[name]': {
                            required: "Product name is quite important",
                            remote: jQuery.format("{0}")
                        }
		}
	});

     $('INPUT[name="product[name]"]').live("keyup",function(){
         var value = $(this).val();

         var elem = $(this);

         if(value.length>2)
         {
            $.ajax({
              url: mooxe.settings.controller+"/search/products/"+value,
              contentType: 'application/json; charset=utf-8',
              success: function(data)
              {
                  var string = 'Similar products: ';

                  var product = '';

                  if(data===false)
                  {
                    string = '';
                  }

                  for( i in data )
                  {
                      if( product!=='' ) string += ", ";
                      product = data[i]['name'];

                      var url = data[i]['url'];

                      string += '<a href="'+url+'">'+product+'</a>';
                      
                  }
                  $('DIV.similar-products').html(string);
              }
            });
         }
     });

    /**
     *
     * Product comment
     *
    **/
    $("#product_comment_form").validate({
            rules: {
                    'product_comment[comment]': {
                        required: true
                    }
            },
            messages: {

                    'product_comment[comment]': {
                        required: "We really would like get your comment"
                    }
            }
    });

    $("#product_comment_form").submit(function(){

        $.ajax({
          url: $(this).attr('action'),
          data: $(this).serialize(),
          type: 'POST',
          dataType: "html",
          success: function(data)
          {
            var comments = $('#comments');
            comments.prepend(data);

            var comment_count = parseInt( $('#comment_count > i:last').text() )+1;

            $('#comment_count > i:last').text( comment_count );

            if( comment_count > 5)
            {
                $('div.comment:first',comments).fadeIn('normal');
                $('div.comment:visible:last',comments).hide();
                
                $('#action_more_comments').show();
            }
            else
            {
                $('div.comment:first',comments).fadeIn('normal');
                
                $('#comment_count > i:first').text( comment_count );
            }

            if( $('#comment_count:hidden').length > 0 )
            {
                $('#comment_count').show();
            }

          }
        });
        return false;
    });

    $("#action_more_comments").click(function(){

        $("DIV.comment:hidden","#comments").each(function(i, elem){
            if( i<5 )
            {
                $(this).fadeIn();
            }
        });

        var comment_count = $("DIV.comment:visible","#comments").length;

        if( $(this).data("comments") )
        {
            if( $(this).data("comments")+5 <= comment_count)
            {
                $(this).data("comments", $(this).data("comments")+5);
            }
            else
            {
                $(this).data("comments", comment_count);
            }
        }
        else
        {

            if( comment_count > 10)
            {
                $(this).data("comments", 10);
            }
            else
            {
                $(this).data("comments", comment_count);
            }
        }


        $('#comment_count > i:first').text($(this).data("comments"));

        if(comment_count == parseInt( $('#comment_count > i:last').text() ) )
        {
            $(this).hide();
        }
        else
        {
            $(this).show();
        }

        return false;
    });

    /*
     *
     * CATEGORY
     *
     */
    
    
    if( page.type == "category" )
    {

        var myTopProducts = $('#myTopProducts');
        var data = { 'category_id' : page.id }
        var updating = false;

        var updateMyProducts = function()
        {
            
            if( myTopProducts.length > 0 && updating === false)
            {
                updating = true;
                
                $.ajax({
                  url: mooxe.settings.controller+"/category/getMyTopProducts",
                  data: data,
                  type: 'GET',
                  dataType: "html",
                  success: function(data)
                  {
                    myTopProducts.html( data );
                    updating = false;
                  }
                });
            }
        }
        
        updateMyProducts();
    }

});

