jQuery(document).ready(function($) {

    /* Benchmarking start */ function t() {var time=new Date();return time.getTime();} var s = t();
    
/**************************************************************************************************************
  * FUNCTIONS
  */

if (location.hostname.indexOf("localhost")>-1) {
    pcs_domain = "http://localhost/nmpsites/";}
else if (location.hostname.indexOf("192.168.21.3")>-1) {
    pcs_domain = "http://192.168.21.3/webdev/201044/nmpsites.co.uk/default/"; 
}else{
    pcs_domain = 'http://'+pcs_domain+'/';
}
    pcs_temp_domain = 'wp-content/themes/'+theme_folder+'/';
    
    //alert(pcs_domain);

/**
 *    TABLE STICKY HEADER
 *    by Xavi Esteve (xaviesteve.com)
 *      Contribution by Damien Wilson (netmediaplanet.com)
 *    Creative Commons Attributive Share-Alike
 *
 *    Sticks table header to the top when scrolling down 
 *        (haven't tried multiple tables in same page but looks like a bad idea)
 *    --- Instructions -----------------
 *    1. Add "stickytable" class to a table
 *    2. Add this CSS: .stickyhead {display:none;position:fixed;top:0;}
 */
 
var $stickytable = $('.stickytable');
var $stickyhead = $('.stickyhead');
if ( $stickytable.length !== 0 ) {
    $('.stickytable thead tr').addClass('sticky_row');
    $('.stickytable thead tr th:first').addClass('sticky_row_img1').css('background-color','#05135e');
    $('.stickytable thead tr th:last').addClass('sticky_row_img2').css('background-color','#05135e');
    $stickytable.before('<table class="stickyhead"><thead>'+$('.stickytable thead').html()+'</thead></table>');
    $(window).scroll(function () {
            var offsettable = $stickytable.offset();
            if ($(window).scrollTop() > offsettable.top && $(window).scrollTop() < (offsettable.top + $stickytable.height()-$stickyhead.height())) {
                $('.stickyhead').css("display", "table");
            }else{
                $('.stickyhead').css("display", "none");
            }
    });
}
$benchres.append( 'stickytable: '+(t()-s)+'ms; ');

var $pcs_keyords = $('#nmp_st_keywords');

// Tool keyword search
var defaultnotext = "Search for other products";
$pcs_keyords.addClass("suggestion").val(defaultnotext).click(function(e){
    if ($(this).hasClass("suggestion")) {$(this).val("");}
        $(this).removeClass("suggestion").css('color','#666');}
        ).blur(function() {
            if ($(this).val()=="") {
                $(this).addClass("suggestion").val(defaultnotext).css('color','#ccc');
        }
    });
$benchres.append( 'toolsearchbox: '+(t()-s)+'ms; ');


/**************************************************************************************************************
  * INITIALIZATION
  */ 
    var screen_size = '';
    var inittool = function (type){
        nmp_st_sort="";
        nmp_st_sortrev = 0;
        
        var obj = new Object();
        var $search_pc = $('#search_pc,#search_pc2');
        var $sl_text = $('#sl_text');
        var $price_start = $("#price_start");
        var $price_stop = $("#price_stop");
        var $slider_price = $("#slider_price");
        var max_stop_val = $price_stop.html();
        var selector_type = 'productfinder';
        
        if ($showmevouchers) {
            $showmevouchers.click(function() { nmp_st('vo','voucherlist',1);return false; });
        }
        
        if(!type||type==null){
            //alert('Tool = ' + tool + ' : Computer Type = ' + type);
            var max_price = 1500; 
            var num_steps = 50;
        }
        
        // PC Finder *****************************************************************
        //alert('Tool = ' + tool + ' : Type = ' + type);
        if ((type=="ha")||(type=="lp")||(type=='pc')||(type=="nb")||(type=='tb')||(type=='ap')) {
            //alert('Tool = ' + tool + ' : Computer Type = ' + type);
            
            var max_price = 1500; 
            var num_steps = 50;
            

        // Anti-Virus *****************************************************************
        }else if (type=="av") {
            var max_price = 100; 
           

        // Software *****************************************************************
        }else if (type=="sw") {
        
            var max_price = 1000;
            var num_steps = 50;
            

        // Reviews *****************************************************************
        }else if (tool=="review") {
            nmp_st("review","",1);
            
        // Game Consoles *****************************************************************
        }else if (type=="gc") {
            
            //alert('Tool = ' + tool + ' : Antivirus Type = ' + type); 
            var max_price = 500;
            var num_steps = 50;
            
        } /* end if tool review */
        
        
        /**
        *   Global Sliders
        * 
        */ /*******************************************************************/
        // Price Slider
        $slider_price.slider({
                range: true,
                min: 0,
                max: max_price,
                values: [0, max_price],
                step: num_steps,
                slide: function(event, ui) {
                    $price_start.html("&pound;"+addCommas(ui.values[0]));
                    $price_stop.html("&pound;"+addCommas(ui.values[1]));
                    if (ui.values[0]===0) {$price_start.html("&pound;0");}
                    if (ui.values[1]==max_price) {$price_stop.html(max_stop_val);}
                }
        });
        // Product Sliders
        var getslider_data = pcs_temp_domain+"setoolparams.php?sid="+blog_id;
        $.getJSON(getslider_data, function(data){
            $.each(data.sliders, function(i,slide) {    
                
                slide_name_id = slide['vars'][0].replace(/ /gi, "_").toLowerCase();
                $slider_hook = $("#slider_"+slide_name_id);
                
                //alert(slide_name_id);
                
                if($slider_hook.length){
                    // Build slider
                    name = slide['vars'][0];
                    max_value = slide['vars'][3];
                    num_steps = 1;
                    
                    //alert('Name = ' + name + ' : id = ' + slide_name_id + ' : Max Value = '+ max_value);
                    $slider_hook.slider({ 
                        value:1, 
                        min: 1, 
                        max: max_value, 
                        step: num_steps, 
                        slide: function(event, ui) {
                            new_switch = 'switch (ui.value) {';
                                for (var i = 2; i <= max_value; i++) {
                                    ib = i-1;
                                    new_switch += 'case '+i+': $sl_text.html(\''+slide[ib]+'\');break; ';
                                }
                            eval(new_switch+'default:$sl_text.html("'+slide[0]+'");}');
                            $slider_hook.val(ui.value);
                        }
                    });
                }
            });
        });
            
        // Do first search
        nmp_st("ha","productfinder",1);
        
        // Bind click event to Search button
        $search_pc.click($searchthroughbut = function() {    nmp_st("ha","productfinder",1); });
        
        // THIS NEED ATTENTION!! Basically, rebuild so when a user hits enter when any form element is in focus, the form submits.
        /*$search_pc.keypress(function (e) {
            if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                 nmp_st("ha",selector_type,1);
                 return false;
            } else {
                return true;
            }
        });*/


    }; /* initool(); */
$benchres.append( 'initool: '+(t()-s)+'ms; ');


 /**************************************************************************************************************
  * PAGINATION
  */

var pagination = function (tool,tableid,page,total){
    // Define vars
    var currpage = parseInt(page, 10);

    $('#pagination,#pagination_2').empty();
    if (page > 1) {
        $("<a />").html("<span class=\"verdana\">&laquo; &nbsp;</span>Prev").attr("href", "#").click(function() {
                nmp_st(tool,tableid,(currpage-1));
                return false;
            }).appendTo("#pagination,#pagination_2").wrap("<span class=\"prev\"></span>");
    }
    for (i = (page-5); i <= (currpage+5); i++) {
        if (page > i) {
            if (i > 0) {
                $("<a />").html(i).attr({href: '#'}).click(function() {
                        nmp_st(tool,tableid,$(this).html());
                        return false;
                }).appendTo("#pagination,#pagination_2").wrap("<span></span>");
            }
        }else if (page==i){
            $("<span />").addClass("active").html(i)
                    .appendTo("#pagination,#pagination_2");
        }else{
            if (i <= total) {
                $("<a />").html(i).attr({href: '#'}).click(function() {
                        nmp_st(tool,tableid,$(this).html());
                        return false;
                }).appendTo("#pagination,#pagination_2").wrap("<span></span>");
            }
        }
    } // end_for
    // Add next button
    if (page < total) {
        $("<a />").html("Next <span class=\"verdana\">&nbsp; &raquo;</span>").attr("href", "#").click(function() {
                nmp_st(tool,tableid,currpage+1);
                return false;
        }).appendTo("#pagination,#pagination_2").wrap("<span class=\"next\"></span>");
    }
    // Update current and total page
    //$('#pages_total').html(total);
    //$('#pages_current').html(page);
};
$benchres.append( 'pagination: '+(t()-s)+'ms; ');




/*********************************************************************************************************************************
 *    AJAX JSON
 * 
 */
//alert(type);
starting = 1;
    var nmp_st = function(tool,tableid,pageno) {
        
        
        // DEFINE VARS
        var $sliderprice = $(".slider_price");
        var $table_select = $('#'+tableid+'>tbody');
        var $nmp_s_phrase = $('#nmp_s_phrase');
        var slider_id = $('#productfinderform>div>div:last').find('div[id^="slider_"]').attr('id');
        var $this_slider = $("#"+slider_id);
        var nmp_st_tool = tool;
        var nmp_st_sid = 2; //$('body').attr('id');
        var nmp_st_pricestart = $sliderprice.slider('values',0); // 0
        var nmp_st_pricestop = $sliderprice.slider('values',1); // 1500
            if (nmp_st_pricestop==1500) {nmp_st_pricestop = "";}
        var nmp_st_slider_val = '';
        var nmp_st_keywords;
        var nmp_st_type;
        var nmp_st_group; // converted from nmp_st_type to support product groups
        var tabcolspan;
        var nmp_st_category;
        var nmp_st_brand;
        var nmp_st_range;
        var nmp_st_usage;
        var i;
        var mydata;
        var jcount;
        var myheaders;
        var toinsert;
        var letterforafflink;
        //var type = prod_type;  
        if (nmp_st_sort == null) {nmp_st_sort="relevance";}
        
        // WATCH OUT WITH THE TRIPLE === DOESNT WORK
        if (nmp_st_brand == null || nmp_st_brand== "") {nmp_st_brand = $('#nmp_st_brand').val();}
        if (nmp_st_brand == null || nmp_st_brand== "") {nmp_st_brand = pcs_brand_nice;}
        if (nmp_st_brand == null) {nmp_st_brand = "";}
        
        // If keywords are 'Search here...' then no keywords @@@
        
        if ($pcs_keyords.hasClass("suggestion") || $pcs_keyords.val()==defaultnotext ) {
            nmp_st_keywords = "";
            if (nmp_st_brand== '' && !nmp_st_range && !nmp_st_usage && nmp_st_pricestart=='0' && nmp_st_pricestop==''){               
            //alert('Brand : '+nmp_st_brand+' | Range : '+nmp_st_range+' | Usage : '+nmp_st_usage+' | Price START : '+nmp_st_pricestart+' | Price STOP : '+nmp_st_pricestop);
            
                // Checks whether there is a search from the home page
                if ($nmp_s_phrase.attr('class')){
                    nmp_st_keywords = $nmp_s_phrase.attr('class').replace("nmp_st_", "");
                    $('#nmp_st_keywords').removeClass('suggestion').val(nmp_st_keywords);
                    //alert(nmp_st_keywords);
                    nmp_st_keywords = nmp_st_keywords;
                }
            }else{
                nmp_st_keywords = "";
            }
                        
        }else{
            nmp_st_keywords = $pcs_keyords.val(); // 
        }    

        nmp_st_page = pageno;
        
        nmp_st_range = $('#nmp_st_range').val(); // family,business,gaming,all
        
        if(slider_id){
            slider_value = $("#"+slider_id).slider("option","value");
            var getsearch_data = pcs_temp_domain+"setoolparams.php?what=search_params&name="+slider_id+"&sid="+blog_id;
            
            $.getJSON(getsearch_data, function(data){
                $.each(data.search_params, function(i,param) {
                 max_value = param.count+1;  
                    for (var i = 2; i <= max_value; i++) {
                        ia = i-2;
                        if (slider_value==i) {nmp_st_slider_val = param[ia]; break;}
                        else if(typeof slider_value=="undefined"){nmp_st_slider_val = ''; break;}
                    }
                    $("#"+slider_id).attr('rel',param.id);
                });
            }); 
        }
        
        var nmp_st_slider_name_id = $this_slider.attr('rel');
        //alert(nmp_st_slider_name_id);
        
        // Specific
        if (tool=="ha") {
            // Product Finder ################################################
                if(!type || type == null || typeof type == 'undefined'){
                    if (type == null){
                        nmp_st_type = $('#nmp_st_type').val();
                        alert('IF = nmp_st_type : '+nmp_st_type+' | type : '+type);
                    }
                    if (type == null) {
                        type = '';
                        nmp_st_type = '';
                        alert('ELSE IF = nmp_st_type : '+nmp_st_type+' | type : '+type);
                    }
                } else {
                    nmp_st_type = type;
                    //alert('ELSE = nmp_st_type : '+nmp_st_type+' | type : '+type);
                }
                
            if (type=="av") {
                // AV ##################################################
                if (nmp_st_pricestop==100) {nmp_st_pricestop = "";} // maximum value = nolimit --> send empty
                
            }else if (type=="sw") {
                // Software ##################################################
                if (nmp_st_pricestop==1000) {nmp_st_pricestop = "";} // maximum value = nolimit --> send empty
                
            }else if (type=="gc") {
                // Games Consoles ##################################################
                if (nmp_st_pricestop==500) {nmp_st_pricestop = "";} // maximum value = nolimit --> send empty
                //alert(nmp_st_group); 
            }
        }else if (tool=="vo") {
            // Voucher ##################################################
            nmp_st_tool = "vouchers";
            nmp_st_category = $('#categoryname').html();
        }
        //alert('Table id : '+ tableid);
        // SEND
        $table_select.fadeTo(50,0.33); 
        
            
                /**
                * 
                *    Set a cookie to store the searched information should a user click out of the page
                * 
                
                
                    var date = new Date();
                    date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000));
                    var searchdata = nmp_st_keywords+'|'+nmp_st_brand+'|'+nmp_st_pricestart+'|'+nmp_st_pricestop+'|'+nmp_st_screen_size+'|'+nmp_st_type+'|'+nmp_st_group+'|'+nmp_st_category+'|'+nmp_st_prospeed+'|'+nmp_st_page;
                
                    $.cookie('nmp#st_results', searchdata, { path: '/', expires: date });
                    newcookie = $.cookie('nmp#st_results');
                    
                    //alert(newcookie);    

                */
                
                
        //alert(nmp_st_slider_val);
        // Prepare query
        if (tool=="ha") {
                jsonquery = "product_search.php?nmp_st_tool="+nmp_st_tool+"&nmp_st_sid="+nmp_st_sid+"&nmp_st_pricestop="+nmp_st_pricestop+"&nmp_st_pricestart="+nmp_st_pricestart+"&nmp_st_page="+nmp_st_page+"&nmp_st_keyword="+nmp_st_keywords+"&nmp_st_sort="+nmp_st_sort+"&nmp_st_sortrev="+nmp_st_sortrev+"&nmp_st_range="+nmp_st_range+"&nmp_st_brand="+nmp_st_brand+"&nmp_st_type="+nmp_st_type+"&nmp_st_slider_val="+nmp_st_slider_val+"&nmp_st_slider_name="+nmp_st_slider_name_id;             
        }
        
        else if (tool=="vouchers") {
            jsonquery = pcs_domain+"product_search.php?nmp_st_tool="+nmp_st_tool+"&nmp_st_sid="+nmp_st_sid+"&nmp_st_pricestop="+nmp_st_sort+"&nmp_st_pricestart="+nmp_st_pricestart+"&nmp_st_page="+nmp_st_page+"&nmp_st_keyword="+nmp_st_keywords+"&nmp_st_sort=price&nmp_st_sortrev="+nmp_st_sortrev+"&nmp_st_brand="+nmp_st_brand.replace("-smb", "")+"";
        }
        /*if (pageno===0) {
            jsonquery = jsonquery + "&nmp_st_recommended";
        }*/
        // Send query
        $.getJSON(jsonquery, function(data){
        // Once received
            $table_select.empty();
            window.total_results = data.total_results;
        // Errors?
            if (data.error) {
                // Opacity to 100
                $table_select.fadeTo(50,1); 
                switch(data.error) {
                    case "noresults":
                        if (tool=="ha") {
                            if (typeof pcs_brand_url=="string") {
                                $table_select.html("<tr><td colspan='"+tabcolspan+"' class='big breathpw'>We have no products that match your search. Find the latest deals at <a href='"+pcs_brand_url+"'>"+pcs_brand_nice+"'s Official Site</a>.</td></tr>");
                            }else{
                                $table_select.html("<tr><td colspan='"+tabcolspan+"' class='big breathpw'>We have no products that match your search.");
                            }
                        } else if (tool=="vo") {
                            if (typeof pcs_brand_url=="string") {
                                $table_select.html('<tr><td colspan="'+tabcolspan+'" class="big breathpw">We have no vouchers available at the moment for '+pcs_brand_nice+', check the <strong><a href="'+pcs_brand_url+'">'+pcs_brand_nice+'\'s Official Site</a></strong>.</td></tr>');
                            }else{
                                $table_select.html('<tr><td colspan="'+tabcolspan+'" class="big breathpw">We have no vouchers available at the moment.</td></tr>');
                            }
                        }
                        else if (tool=="review") {
                            if (typeof pcs_brand_url=="string") {
                                $table_select.html('<tr><td colspan="'+tabcolspan+'" class="big breathpw">We have no reviews available at the moment for '+pcs_brand_nice+', check the <strong><a href="'+pcs_brand_url+'">'+pcs_brand_nice+'\'s Official Site</a></strong>.</td></tr>');
                            }else{
                                $table_select.html('<tr><td colspan="'+tabcolspan+'" class="big">We have no reviews available at the moment.</td></tr>');
                            }
                        }
                        else if (tool=="compare") {
                            if (typeof pcs_brand_url=="string") {
                                $('#product_list').html('<div class="span-20 comp_pod">Unfortunatley the product wasn\'t returned to compare.<br /><br />Please try selecting another one product or refresh the page and try again.</div>');
                            }else{
                                $table_select.html('<tr><td colspan="'+tabcolspan+'" class="big">We have no reviews available at the moment.</td></tr>');
                            }
                        }
                    break;
                    case "missingparams":
                        $table_select.html("<tr><td colspan='"+tabcolspan+"' class='big'>Oops! Somethings missing - maybe a parameter?</td></tr>");
                    break;
                    case "unknowntool":
                        $table_select.html("<tr><td colspan='"+tabcolspan+"' class='big'>Sorry, tool not recognised</td></tr>");
                    break;
                    case "sqlerror":
                        $table_select.html("<tr><td colspan='"+tabcolspan+"' class='big'>There was an ERROR in the QUERY</td></tr>");
                    break;
                    default:
                        $table_select.html("<tr><td colspan='"+tabcolspan+"' class='big'>Wow!? We\'ve experienced an unknown error</td></tr>");
                }
                pagination(0,0,0,0,0,0);
                
            }else{ // No error
                
                // ##############  PRODUCT FINDER #############################################
                
                    i = 0;        
                    letterforafflink = "c";
                    if (nmp_st_brand=="dell-smb") {letterforafflink = "b";}
                    // Custom message boxes in first result
                    // Dell Business
                    if (nmp_st_brand=="dell" && nmp_st_range=="business") {
                        toinsert = '<td colspan="7" style="background:#FFF3BD;border:2px solid #ec0;font-size:12px;font-weight:900;margin:0;padding:10px;text-align:center;">Looks like you are searching for Dell Business Computers? <a href="'+pcs_domain+'/dell-business">Click here to go to our <strong>Dell Business</strong> section</a>.</a></td>';
                        $("<tr/>").html(toinsert).appendTo('#'+tableid+'>tbody');
                    }
                    
                    $.each(data.items, function(i,item) {
                        if (item) { // @@@ Loop goes 5 times even when there's less than 5 (try "dell mini" query)
                        
                        // Random product offer text...
                        
                        /*var r_text = new Array ();
                        r_text[0] = "Save money today";
                        r_text[1] = "Click for Xmas offers";
                        r_text[2] = "Check out our deals";
                        r_text[3] = "Save money and time";
                        r_text[4] = "Find offers here";
                        r_text[5] = "Click and save";
                        var i = Math.floor(6*Math.random());*/
                        
                        if(!item.student_link){
                            item.student_link = '';
                        }else{
                            item.student_link = '<a href="'+item.student_link+'" class="hyp-blue breathpn" style="color:blue" rel="nofollow" target="_blank">Student and<br /> Teacher discounts!</a>';
                        }                        
                        if(!item.short_description){
                            item.short_description = '<span class="red">Short Description needed!<span class="red">';}else{
                            item.short_description = item.short_description.substr(0, 100);
                            item.short_description = item.short_description.replace(/\|/g, "<br />");
                        }
                        if(!item.features){item.features = '<span class="red">No fearture text! Please update</span><br /><span class="small">Hover over the link that says <span style="color:blue">Buy now</span>, the product ID is at the end of the URL, after the <span class="medium">/?s</span></span>';}
                        if(!item.existing_customer){
                            item.existing_customer = '<a href="'+pcs_domain+'s/?c'+item.product_id+'&amp;m='+item.merch_1_id+'" class="hyp-blue" rel="nofollow" target="_blank">Upgrade here</a><br />';
                        }else{
                            item.existing_customer = '<a href="'+item.existing_customer+'&amp;m='+item.merch_1_id+'" class="hyp-blue" rel="nofollow" target="_blank">Upgrade here</a><br />';
                        }
                            switch (item.parent_type) {
        /****************  Hardware Case  ****************/ 
                                case 'ha':
                                    pocket_p = item.processor;
                                    pocket_m = item.spec+'<br /><br />'+item.storage;
                                        if(item.abbr_type=='pc'){
                                            item.graphics = item.graphics.substr(0, 100);
                                            item.graphics = item.graphics.replace(/\|/gi, "<br />");
                                            pocket_h = item.graphics; 
                                        }else{
                                            pocket_h = item.screen.replace(/\|/gi, "<br />");
                                        }                       
                                    button_text = 'Find out more';                 
                                          
                                    break;
        /****************  Software Case  ****************/             
                                case 'sw':
                                    
                                    pocket_p = item.short_description;
                                    pocket_m = item.existing_customer;
                                    pocket_h = '<span style="font-size:11px;">'+item.features+'</span>';
                                    button_text = 'Find out more';
                                    item.quote = '<br />';
                                    
                                    break;
        /****************  Antivirus Case  ****************/ 
                                case 'av':
                                
                                    pocket_p = item.short_description;
                                    //pocket_m = '<a href="/s/?a'+item.product_id+'&amp;m='+item.merch_1_id+'" class="hyp-blue" target="_self">I already own a previous version of '+item.title+'</a><br /><br /><a href="'+item.url+'" class="hyp-blue" target="_self">Get 3 users protected</a>';                                
                                    pocket_m = '<a href="/s/?a'+item.product_id+'&amp;m='+item.merch_1_id+'" class="hyp-blue" target="_self">I already own a previous version of '+item.title+'</a>';
                                    pocket_h = '<span style="font-size:11px;">'+item.features+'</span>';
                                    button_text = 'Download Now';
                                    item.quote = '<br />';
                                                     
                                    break;
        /****************  Gaming Console  ****************/ 
                                case 'gc':
                                
                                    pocket_p = item.hard_drive_storage;
                                    pocket_m = item.accessories+'<br /><br />'+item.ports.replace(/\|/g, "<br />");
                                    pocket_h = item.hardware_included.replace(/\|/g, "<br />");
                                    button_text = 'Find out more';
                                    item.quote = '<br />';
                                                     
                                    break;
                            }
                            
                            /**
                            *  Support for multiple merchants
                             ----------------------------------------- */
                            var merch_count = item.merch_count;
                            if (merch_count>1){
                                multimerch = '<ul class="merch_list">\n';
                                for (mc=1;mc<=merch_count;mc++){
                                    eval("var merch_name = item.merch_"+mc+";var merch_id = item.merch_"+mc+"_id;var merch_price = item.merch_"+mc+"_price;if(typeof item.merch_"+mc+"_imp_cookie == 'undefined'){var merch_imp_cookie = '';}else{var merch_imp_cookie = item.merch_"+mc+"_imp_cookie;}");
                                    merchant = merch_name.toLowerCase();
                                    merchant = merchant.replace(" ", "");
                                    if(mc==merch_count){
                                        li_class = 'multi_merch nobreaths';
                                    }else{
                                        li_class = 'multi_merch';
                                    }
                                    if(merch_imp_cookie=='undefined'){
                                        merch_imp_cookie = '';
                                    }
                                    multimerch += '<li class="'+li_class+'"><a href="'+pcs_domain+'s/?c'+item.product_id+'&amp;m='+merch_id+'" title="'+merch_name+'" class="hyp-blue medium pref'+mc+'" style="line-height:23px;display:block" rel="nofollow" target="_blank"><img src="'+pcs_domain+'wp-content/themes/pcsite/images/merchants/merchant-'+merchant+'.jpg" alt="'+merch_name+'" class="fleft" /><span class="fright">&pound;'+addCommas(merch_price)+'</span></a>'+merch_imp_cookie+'</li>\n';
                                    
                                }
                                multimerch += '</ul>';
                                merch_output = multimerch;
                                
                            }else{
                                merchant = item.merch_1.toLowerCase();
                                merchant = merchant.replace(" ", "");
                                if(typeof item.merch_1_imp_cookie == 'undefined'){
                                    var merch_imp_cookie = '';
                                }else{
                                    var merch_imp_cookie = item.merch_1_imp_cookie;
                                }                            
                                merch_output = '<div class=""><p><a href="'+pcs_domain+'s/?c'+item.product_id+'&amp;m='+item.merch_1_id+'" class="hyp-blue medium pref1" rel="nofollow" style="line-height:23px;display:block" target="_blank"><img src="'+pcs_domain+'wp-content/themes/pcsite/images/merchants/merchant-'+merchant+'.jpg" alt="'+merchant+'" style="padding-top:3px;" /><span class="fright">&pound;'+addCommas(item.merch_1_price)+'</span></a><br />'+item.student_link+'<br /><a href="'+pcs_domain+'s/?c'+item.product_id+'&amp;m='+item.merch_1_id+'" class="butsmall green" rel="nofollow" target="_blank">'+button_text+'<span>GO</span></a></p>'+merch_imp_cookie+'</div>\n';
                            }
                            if($.cookie('__nmp_product_edit')=='on'){
                                edit_prod = '<a href="/pdm/?f=update_product&product_id='+item.product_id+'" class=\"pencil\" target="_blank"></a>';
                            }else{
                                edit_prod = '';
                            }
                            /**
                            *  Build Product Rows
                             ----------------------------------------- */
                                                          
                            var toinsert = '<td class="i prodclick relative">'+edit_prod+'<img src="'+pcs_domain+'wp-content/themes/pcsite/images/products/'+item.image+'" style="width:120px" class="comp_prod_img" /></td>\n<td class="n prodclick"><p style="height:40px;overflow:hidden;">'+item.title+'</p><div class="st_img"><div class="star_rate"><div style="width:'+item.star_rating+'%; display: block;">&nbsp;</div></div></div><p class="small">'+item.quote+'</p><a href="'+item.review_link+'" class="hyp-blue small rev_lnk">Read the expert review</a></td>\n<td class="p prodclick">'+pocket_p+'</td>\n<td class="m prodclick">'+pocket_m+'</td>\n<td class="h prodclick">'+pocket_h+'</td>\n<td class="v prodclick">';
                                    
                            if (item.offer>0) { // if it is a number
                                toinsert += '<div class="round bblue"><p class="white"><span class="strong">save more than</span><br /><span class="huge strong">&pound;'+addCommas(item.offer)+'</span><br /><span class="strong">TODAY!</span></p></div>';
                            }else if (item.offer) { // if it is anything else
                                toinsert += '<div class="round bblue"><p class="white" style="padding-top:5px;"><span class="strong">'+item.offer+'</span></p></div>';
                            }else{
                                toinsert += '<div class="round bblue breathpns"><p class="white" style="padding-top:5px;"><span class="strong medium">Click for latest offers</span></p></div>';
                            }
                            
                            toinsert += '</td>\n<td class="c"><div class="relative breathpe"><div id="comp_'+item.product_id+'" class="abs_comp_but hide bblue"><div class="comp_arrow"></div><span class="img_compare">&nbsp;</span><span class="radio_off">&nbsp;</span></div>'+merch_output+'</div></td>\n';
                            //alert(toinsert);
                            
                            $("<tr/>")
                                .attr("id", "item-"+item.product_id)
                                .attr("rel","nofollow")
                                .attr("valign","top")
                                .attr("title", "Buy "+item.title+"")
                                .html(toinsert)
                                .appendTo('#'+tableid+'>tbody'); 
                                
                        }
                    }); //end_each
                    bindHover($('tr[id^=item-]'));
                    bindClick($('div[id^="comp_"]'));
                    //alert(data.total_results);
                    
                    /**
                     *    Table Row format and events
                     */ 
                    $("#pc-memory,#pc-hd,#pc-price").each(
                        function () {
                        $(this)
                            .attr("title", "Sort by "+$(this).html())
                            /*.addClass("sortable")*/
                            .unbind("click");
                            /*.click(sortable_th($(this).attr("id"),tool,tableid,nmp_st_page));*/
                        }
                    );
                    
                    var lnk_processed = 0;
                    $('.stickytable .prodclick').each(function () {
                        $('.rev_lnk').click(function(){
                            window.location = $(this).attr('href');
                            lnk_processed = 1;
                            return false;
                        });
                        $(this).click(function(){
                            if(lnk_processed==0){
                                // pref1 added to support multiple merchants
                                var newWindow = window.open($("#"+$(this).parent().attr('id')+" a.pref1" ).attr("href"), '_blank');
                                newWindow.focus();
                            }
                        //alert(lnk_processed);
                        });
                    });
                    
                    $('span.amount_bx b, span#amounts b').html(total_results);
                    $(".round").corner("round 6px keep");
                
                /**
                 *    Tidy up
                 */
                if (tool!="vo") {
                    if (starting === 0) {scrollWin ("#"+tableid);}
                    starting = 0;
                    pagination(tool,tableid,nmp_st_page, data.total_pages);
                }
                $table_select.fadeTo(50,1);
            } 
        }); 
    };
$benchres.append( 'pagination: '+(t()-s)+'ms; ');

//alert('Tool = ' + tool + ' : Type = ' + type);
inittool(type);

$benchres.append( 'initoolexec: '+(t()-s)+'ms; ');

/*********************************************************************************************************************************
 *    BIND EVENTS
 * 
 */
 
// Tool keyword search
var defaultnotext = "Search for other products";
if ($pcs_keyords.val()=="") {
    $pcs_keyords
        .addClass("suggestion")
        .val(defaultnotext)
        .click(function(e){
            if ($(this).hasClass("suggestion")) {$(this).val("");}
            $(this).removeClass("suggestion")
                .css('color','#666');})
        .blur(function() {
            if ($(this).val()=="") {
                $(this).addClass("suggestion")
                .val(defaultnotext).css('color','#ccc');
            }
        });
}
$benchres.append( 'toolsearchbox: '+(t()-s)+'ms; ');

// Keyword Enter key
$pcs_keyords.keyup(function(e) {
    if (e.keyCode == 13) {
        if ($("#computerfinder").length !== 0) {
            nmp_st("ha","computerfinder",1);
        }else if ($("#pcbfinder").length !== 0) {
            nmp_st("pc-business","pcbfinder",1);
        }else if ($("#avselector").length !== 0) {
            nmp_st("av","avselector",1);
        }else if ($("#swselector").length !== 0) {
            nmp_st("sw","swselector",1);
        }else if ($("#reviewfinder").length !== 0) {
            nmp_st("review","reviewfinder",1);
        }
    }
});


// function Add Commas to numbers
function addCommas(nStr){
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

$benchres.append( 'other: '+(t()-s)+'ms; ');

/* Replace jQ UI slider with text boxes */
if($.browser.msie && $.browser.version==6.0 ){
    //$('#price_start').replaceWith('&pound; <input type="text" id="price_start_i" value="0" /> ');
    //$('#price_stop').replaceWith('&pound; <input type="text" id="price_stop_i" value="1000" /> ');
    var $price_sta_i = $('#price_start_i');
    var $sli_price = $("#slider_price");
    $price_sta_i.change(function() { 
        $sli_price.slider( "values", 0, $price_sta_i.val() );
    });
    $price_sta_i.change(function() { 
        $sli_price.slider( "values", 1, $price_sta_i.val() );
    });
}


/* Benchmarking end */
$benchres.append( 'pcsite-tool.js: '+(t()-s)+'ms; ');

}); // end ready
