$(window).load(function ()
{
    $("#search-how-to").autocomplete('/how_to/auto_suggest', {
        width : 507, max : 10, highlight : false, selectFirst : false, scroll : true, scrollHeight : 300 
    });
    // "Helpful / Not Really Helpful" on "How to page"
    $('.btn_helpful').click( function () 
    {
        var site_url = $('#site_url').val();
        var user_id = $("#userid");
        var content_type = $("#content_type");
        var remote_id = $("#remoteid");
        var rate_data = $(this).attr('rel');
        var bln_rate;
        var url = $(this).attr('href');
        var sid = (Math.round((Math.random() * 9) + 1));
        var refresh_count;
        var feedback_text = $(this).parent();
        //var block_panel	=	$(this).parent();
        rating_data = rate_data.split("|");
        bln_rate = rating_data[0];
        refresh_count = $("#" + rating_data[1]).text();
        var data = Array();
        data.push( 'content_type=' + content_type.val() );
        data.push( 'remoteid=' + remote_id.val() );
        data.push( 'rating=' + bln_rate );
        var params = data.join('&');
        if (!user_id.val()) 
        {
            ajax_data = params;
            ajax_url = site_url + '/ratings/rate?sid=' + sid;
            redirect = $("#diy_url").val();
            $.show_login();
            return;
        }
        var params = params + '&userid=' + user_id.val();
        // do ajax call
        $.ajax(
        {
            type : 'post', url : '/ratings/rate?sid=' + sid, data : params, dataType : 'json', async : false, 
            beforeSend : function () 
            {
                //prompt_activity( block_panel, "Please wait..." );
                //block_panel.block({ message: "Please wait..." });
            },
            success : function ( data ) 
            {
                if (data.response == 'success') 
                {
                   
                    if (data.current_rating != bln_rate) 
                    {
                    	val_new_rate = (bln_rate == 1) ? parseInt(refresh_count) + 1 : refresh_count - 1; 
                    	$("#" + rating_data[1]).text(val_new_rate);
                        feedback_text.html('<span style="float:left;color:#016D95;">Thanks for your vote!</span>');
                    }
                    else 
                    {
                        feedback_text.html('<span style="float:left;color:#016D95;">Your vote was already saved!</span>');
                    }
                }
                else 
                {
                    alert( data.response );
                }
            },
            error : function () 
            {
                alert( "An error occured.\nPlease try again later." );
            }
        }); 
        return false;
    });
    // "Helpful / Not Really Helpful" on "How to page"
    $('.btn_video_helpful').click( function () 
    {
        var site_url = $('#site_url').val();
        var user_id = $("#userid");
        var content_type = $("#video_content_type", $(this));
        var remote_id = $("#video_remoteid", $(this));
        var rate_data = $(this).attr('rel');
        var bln_rate;
        var url = $(this).attr('href');
        var sid = (Math.round((Math.random() * 9) + 1));
        var refresh_count;
        var feedback_text = $(".helplink");
        //var block_panel	=	$(this).parent();
        if (!user_id.val()) {
            $.show_login();
            return;
        }
        rating_data = rate_data.split("|");
        bln_rate = rating_data[0];
        refresh_count = $("#" + rating_data[1]).text();
        var data = Array();
        data.push( 'content_type=' + content_type.val() );
        data.push( 'remoteid=' + remote_id.val() );
        data.push( 'rating=' + bln_rate );
        var params = data.join('&');
        if (!user_id.val()) 
        {
            ajax_data = params;
            ajax_url = site_url + '/ratings/rate?sid=' + sid;
            redirect = $("#diy_url").val();
            $.show_login();
            return;
        }
        var params = params + '&userid=' + user_id.val();
        // do ajax call
        $.ajax(
        {
            type : 'post', url : '/ratings/rate?sid=' + sid, data : params, dataType : 'json', async : false, 
            beforeSend : function () 
            {
                //prompt_activity( block_panel, "Please wait..." );
                //block_panel.block({ message: "Please wait..." });
            },
            success : function ( data ) 
            {
                if (data.response == 'success') 
                {
                    //prompt_activity( block_panel, "Rating sent..." );
                    //$( block_panel ).unblock();
                    //alert( "Your rate has been submitted!" );
                    if (data.current_rating != bln_rate) 
                    {
                        val_new_rate = (bln_rate == 1) ? parseInt(refresh_count) + 1 : refresh_count - 1; 
                        $("#" + rating_data[1]).text(val_new_rate);
                        feedback_text.html('<span style="float:left;color:#016D95;">Thanks for your vote!</span>');
                    }
                    else 
                    {
                        feedback_text.html('<span style="float:left;color:#016D95;">Your vote was already saved!</span>');
                    }
                }
                else 
                {
                    //prompt_activity( block_panel, data.response );
                    //$( block_panel ).block({ message: data.response });
                    alert( data.response );
                }
            },
            error : function () 
            {
                alert( "An error occured.\nPlease try again later." );
            }
        });
        return false;
    });    
    // allow video upload for logged users only
    $('.share-yours').click(function ()
    {
        var site_url = $('#site_url').val();
        var url = $('#upload_url').val();
        var userid = $('#userid').val();
        if (!userid) {
            $.ubox(site_url + '/user/login?url=' + url);
            return;
        }
        location = url;
    });
    
    $(".how-to-heroshot-display div").hide();
    $("ul.tabs li:first").addClass("current").show();
    $(".how-to-heroshot-display div:first").show();
    $("ul.tabs li").click(function () 
    {
        $("ul.tabs li").removeClass("current");
        $(this).addClass("current");
        $(".how-to-heroshot-display div").hide();
        var activeTab = $(this).find("a").attr("href");
        $(activeTab).show();
        return false;
    });
    $('.btn_improve_step').click(function () 
    {
        var site_url = $("#site_url").val();
        var url = $(this).attr('href');
        if ($.ubox) {
            $.ubox(site_url + url);
        };
        return false;
    }) // contributor names
    $('.more_names').hide();
    $('.show_more_names').click(function () 
    {
        //$(this).parent(0).html('');
        $('.more_names').show();
        $(this).parent().hide();
    }); 
    $(".btn-continue").click(function ()
    {
        if ($('#how-to-year').val() == '') {
            alert("Please select year, make and model to continue.");
            return false;
        }
        if (($('#how-to-make').val() == '' || $('#how-to-make').val() == undefined)) {
            alert("Please select make and model to continue.");
            return false;
        }
        if (($('#how-to-model').val() == '' || $('#how-to-model').val() == undefined)) {
            alert("Please select model to continue...");
            return false;
        }
    }); 
    $("#howto-sidebar-find-shop").submit(function ()
    {
        /** Set Analytics Data **/
        var scevar = [];
        scevar['eVar1'] = $('#find-shop-name').val();
        var scevent = ['event4']; 
        sclinkCode(s_account, 'Find a Shop', scevent, scevar);
        /** Set Analytics Data **/
    });
    /* email this article button */
    $("a.btn_email_article").click(function () 
    {
        // check first if ubox was loaded
        if ($.ubox) {
            // fire ubox popup
            var pop_url = $(this).attr('rel');
            $.ubox(pop_url);
        }
        return false;
    }) /* fix 4767 spinbutton */
    var all_wrapper = $("div#all");
    $("div#estimatebox").hover( function ()
    {
        all_wrapper.css('position', 'static');
    },
    function ()
    {
        all_wrapper.css('position', 'relative');
    }); 
    $("form#how_to_search_module").submit(function () 
    {
        var this_text = $("input#search-how-to", this);
        if (this_text.val() == '' || this_text.val() == 'Enter keywords, or problem') {
            alert('Please enter a keyword/s to search');
            return false;
        }
    }) /* UGC edits to how to guides */
    var validate_user = function (r) 
    {
        if ($('#userid').val()) {
            return true;
        }
        else {
            redirect = $("#diy_url").val();
            $.show_login();
            return;
        }
    }
    /* HOW-TO GUIDE DETAIL */
    var parent = $('.verified-tab-nav');
    $('li', parent).click(function ()
    {
        var part = $(this).attr('class');
        if (part == 'v-part') {
            $('.display-tab').hide();
            $('.watch-video-tab').show();
        }
        else {
            $('.display-tab').show();
            $('.watch-video-tab').hide();
        }
        $('a', parent).removeAttr('class');
        $('a', this).attr('class', 'current');
    }); 
    $('.right-tab-c').each(function ()
    {
        var par = this;
        $('.fold', par).click(function ()
        {
            var txt = $(this).html();
            var label = $(this).attr('rel');
            if (txt == '(Show)') 
            {
                $('.tcount', par).hide();
                $('.matt', par).stop().show();
                $('.clear img', par).attr('src', '/images/arrow-down-ico.jpg');
                $(this).html('(collapse)');
            }
            else 
            {
                $('.tcount', par).show();
                $('.matt', par).hide();
                $('.clear img', par).attr('src', '/images/arrow-right-ico.jpg');
                $(this).html('(Show)');
            }
        }) 
    }); 
    $('.btn-view-details').unbind("click").click(function ()
    {
        var year_id = $('#year_id').val();
        var make_id = $('#make_id').val();
        var model_id = $('#model_id').val();
        var submodel_id = $('#submodel_id').val();
        var engine_id = $('#engine_id').val();
        var diy_id = $('#diy_id').val();
        var zip = $('#zip').val();
        var diagnosis_key = $('#diagnosis_key').val();
        var scPage = $('#scPage').val();
        var site_url = $('#site_url').val();
        //var redirect = $('#current_page').val();
        /*schandleOnclickEvent('s_account','/repaircost/detail?{if $vehicles}year={$vehicles[0].year.year_id}&make={$vehicles[0].make.make_id}&model={$vehicles[0].model.model_id}{if
        $vehicles[0].submodel.submodel_id}&submodel={$vehicles[0].submodel.submodel_id}{/if}{if $vehicles[0].engine.engine_id}&engine={$vehicles[0].engine.engine_id}{/if}{/if}&jobs[]={$diy_id}&zip={$location.zip}{if
        $diagnosis_key}&key={$diagnosis_key}{/if}','event6', 'eVar2', null, 'Cost Estimate', '{$scPage}');*/
        var url = '/repaircost/detail?year=' + year_id + '&make=' + make_id + '&model=' + model_id + '&jobs[]=' + diy_id + '&zip=' + zip;
        if (submodel_id) {
            url = url + '&submodel=' + submodel_id;
        };
        if (engine_id) {
            url = url + '&engine=' + engine_id;
        };
        if (diagnosis_key) {
            url = url + '&key=' + diagnosis_key;
        };
        if (!year_id || !make_id || !model_id || !submodel_id || !engine_id ) 
        {
            $.ubox(site_url + '/how_to/vehicle_select/?diy_id=' + diy_id + '&zip=' + zip + '&method=get&action=/repaircost/detail/&t=1');
            return;
        }
        else 
        {
            schandleOnclickEvent('s_account', url, 'event6', 'eVar2', null, 'Cost Estimate', scPage);
        }
    });
    $(".lb-how-to-btn-continue").live('click', function ()
    {
        var engine = $("#how-to-engine").val();
        if (engine == '') {
            alert('Please select year, make, model, submodel and engine to continue.');
            return;
        }
        else {
            $('#how-to-carpicker').submit();
        }
    });
    var total_page = AMD.total_page;
    var curr_page = 1;
    $(".previous").hide();
    $("#pagination a").click( function ()
    {
        var rel = $(this).attr('rel');
        var parent_cl = $(this).parent("li").attr("class");
        var prev = $("#pagination li.previous");
        var next = $("#pagination li.next");
        $("div.howto-list").hide();
        $("#howto-" + rel).fadeIn();
        curr_page = parseInt(rel);
        $("#pagination li").removeClass("active");
        if (parent_cl != 'next' && parent_cl != 'previous') {
            $(this).parent("li").addClass("active");
        }
        else
        {
            $("#pagination li").each( function ()
            {
                if (parseInt($(this).find("span").html()) == curr_page) {
                    $(this).addClass("active");
                }
            });
        }
        prev.find("a").attr("rel", curr_page - 1);
        next.find("a").attr("rel", curr_page + 1);
        if (curr_page == 1) {
            prev.hide();
            next.show();
        }
        else if (curr_page >= (total_page) ) {
            prev.show();
            next.hide() 
        }
        else {
            prev.show();
            next.show();
        }
        return false;
    });
    $('#matt').html($('#more_0').html());
    $('.previous').hide();
    $('.page').click(function ()
    {
        $('.page').removeClass('active');
        $(this).addClass('active');
        var page = $(this).find('span').html() - 1;
        var p = page + 1;
        $('#matt').html($('#more_' + page).html());
        $('#page').val(p);
        //alert(page);
        //alert(p);
        if (p == 1) {
            $('.previous').hide();
        }
        if (p > 1) {
            $('.previous').show();
        }
        if (p == $('#max_page').val()) {
            $('.next').hide();
        }
        else {
            $('.next').show();
        }
    });
    $('.next').click(function ()
    {
        var page = parseInt($('#page').val());
        var p = page + 1;
        if (p > 1) {
            $('.previous').show();
        }
        if (p == $('#max_page').val()) {
            $('.next').hide();
        }
        if (page < $('#max_page').val()) {
            $('#matt').html($('#more_' + page).html());
            $('#page').val(p);
            activate(p);
        }
    });
    $('.previous').click(function ()
    {
        var page = parseInt($('#page').val());
        var p = page - 1; 
        if (p == 1) {
            $('.previous').hide();
        }
        if (page > 1)
        {
            var key = parseInt(page - 2);
            $('#matt').html($('#more_' + key).html());
            $('#page').val(p);
            activate(p);
            $('.next').show();
        }
    });
    var activate = function (p)
    {
        $('.page').removeClass('active');
        $('.page').each(function ()
        {
            if ($(this).find('span').html() == p) {
                $(this).addClass('active');
            }
        }) 
    }
    $("a.video-popup").click(function ()
    {
        var vid = $(this).attr('rel');
        $.ubox(site_url + '/how_to/video_play/?videoid=' + vid);
    });
});