(function( $, undefined ) {
  if ($.ui && $.ui.dialog) {
    $.ui.dialog.overlay.events = $.map('focus,keydown,keypress'.split(','), function(event) { return event + '.dialog-overlay'; }).join(' ');
  }
}(jQuery));

// START OF DROPDOWN AUTOCOMPLETE FOR CLASSIFICATION
(function ($) {
    $.widget("ui.combobox", {
        _create: function () {
            var self = this,
                select = this.element.hide(),
                selected = select.children(":selected"),
                value = selected.val() ? selected.text() : "";
            var input = this.input = $("<input id=\"inp\">").insertAfter(select).val(value).autocomplete({
                delay: 0,
                minLength: 0,
                source: function (request, response) {
                    var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                    response(select.children("option").map(function () {
                        var text = $(this).text();
                        if (this.value && (!request.term || matcher.test(text))) return {
                            label: text.replace(
                            new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(request.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "$1"),
                            value: text,
                            option: this
                        };
                    }));
                },
                select: function (event, ui) {
                    ui.item.option.selected = true;
                    self._trigger("selected", event, {
                        item: ui.item.option
                    });
                },
                change: function (event, ui) {
                    if (!ui.item) {
                        var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
                            valid = false;
                        select.children("option").each(function () {
                            if ($(this).text().match(matcher)) {
                                this.selected = valid = true;
                                return false;
                            }
                        });
                        if (!valid) {
                            // remove invalid value, as it didn't match anything
                            $(this).val("");
                            select.val("");
                            input.data("autocomplete").term = "";
                            return false;
                        }
                    }
                }
            }).addClass("ui-widget ui-widget-content ui-corner-left hp_select");
            input.data("autocomplete")._renderItem = function (ul, item) {
                return $("<li></li>").data("item.autocomplete", item).append("<a>" + item.label + "</a>").appendTo(ul);
            };
            this.button = $("<button type='button'>&nbsp;</button>").attr("tabIndex", -1).attr("title", "Show All Items").insertAfter(input).button({
                icons: {
                    primary: "ui-icon-triangle-1-s"
                },
                text: false
            }).removeClass("ui-corner-all").addClass("ui-corner-right ui-button-icon").click(function () {
                // close if already visible
                if (input.autocomplete("widget").is(":visible")) {
                    input.autocomplete("close");
                    return;
                }
                // work around a bug (likely same cause as #5265)
                $(this).blur();
                // pass empty string as value to search for, displaying all results
                input.autocomplete("search", "");
                input.focus();
                $('html body.hp_body ul.ui-autocomplete:eq(0)').css('width', '450px');
            });
        },
        destroy: function () {}
    });
})(jQuery);
// DROPDOWN AUTOCOMPLETE FOR CLASSIFICATION END

// START OF DOCUMENT READY
$(function () {

// SHARE START - HOVER 
$('.share_link').hoverIntent(function () {
    trigger = $(this);
    show_share(trigger);
	rem_toolbar_bg();
	$('.tb_share').css('background-color','#ffffff');
}, function () {});
$('#share_wrapper').mouseleave(function () {
    $('#share_wrapper').addClass('hide');
	rem_toolbar_bg();
});
// SHARE END
// SAVE START  - HOVER
$('.save_link').hoverIntent(function () {
    trigger = $(this);
    show_save(trigger);
	rem_toolbar_bg();
	$('.tb_save').css('background-color','#ffffff');
}, function () {});
$('#save_wrapper').mouseleave(function () {
    $('#save_wrapper').addClass('hide');
	rem_toolbar_bg();
});
$(document).delegate(".ui-widget-overlay,.lg_pv_header,.pv_close_btn", "mouseenter", function(){    
$('#save_wrapper').addClass('hide');
	$('#share_wrapper').addClass('hide');
	});
	
	$(document).delegate("html div#at20mc div#at16pcc div#at16p,html body div#at20mc div#at16lb,#share_wrapper,html body div#share_wrapper.addthis_32x32_style table tbody tr td#sharebtn1,html body div#share_wrapper.addthis_32x32_style table tbody tr td a.addthis_button_email","mouseover", function(){    
$('html div#at20mc div#at16pcc div#at16p div#at16pib div#at16pi div#at16pm div#at16pt h4 span#at16ptc').html('Email this product information');
$('html div#at20mc div#at16pcc div#at16p div#at16pib div#at16pi div#at16pm div#at16pc div#at_email form label:eq(0)').html('To:  <span>(separate email addresses by a comma)</span>');
$('html div#at20mc div#at16pcc div#at16p div#at16pib div#at16pi div#at16pm div#at16pc div#at_email form textarea#at_to:eq(0)').keyup(function() {
$('html div#at20mc div#at16pcc div#at16p div#at16pib div#at16pi div#at16pm div#at16pc div#at_email form textarea#at_to').val($('html div#at20mc div#at16pcc div#at16p div#at16pib div#at16pi div#at16pm div#at16pc div#at_email form textarea#at_to:eq(0)').val().replace(/ /g,''));
});
	});


function rem_toolbar_bg(){
$('.tb_share').removeAttr('style');
$('.tb_save').removeAttr('style');
}
// SAVE END ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 
// SUBMIT SEARCH FORM WITH ENTER CLICK
    $('#bpm').keypress(function (e) {
        if (e.which == 13) {
           form_check();
           e.preventDefault();
        }
    });
// // SUBMIT SEARCH FORM WITH ENTER CLICK END //////////////////////////////////////////////////////////////////////////////////////////

// SUBMIT LOGIN FORM WITH ENTER CLICK

	$(document).delegate("#bpmlogin input, #bpmlogin select", "keypress", function(e){    
if(e.keyCode==13){
                bpm_login_submit();
           e.preventDefault();
        }
	});
	


// // SUBMIT LOGIN FORM WITH ENTER CLICK END //////////////////////////////////////////////////////////////////////////////////////////



// BOOKMARKS MENU START ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
$('#bookmarks_link').hoverIntent(function () {
        $('.bookmarks_menu').css('display', 'block');
		 $.ajax({
            url: 'index.php?id=11&userid='+$('.login_link').attr('id'),
			//url: 'index.php?id=11',
            success: function (data) {

			$('.bookmark_content_wrapper').html(data);
						$('.bm_single_result').mouseenter(function() {
  $('.bm_active').removeClass('bm_active');
  $(this).addClass('bm_active');
});
			$( ".bm_init_prod img" ).aeImageResize({ height: 90, width: 90 });
			
			var seen = {};
$('.manu_list_bm a').each(function() {
    var txt = $(this).text();
    if (seen[txt])
        $(this).parent().remove();
    else
        seen[txt] = true;
});

			var seen2 = {};
$('.manu_list_bm_csi a').each(function() {
    var txt = $(this).text();
    if (seen2[txt])
        $(this).parent().remove();
    else
        seen2[txt] = true;
});

	 // IE 8 manu_list onchange fix 
	 if ($.browser.msie && parseInt($.browser.version, 10)==8) {
 $('.manu_list_bm input').each(function(){ $(this).attr('onclick',$(this).attr('onchange')).removeAttr('onchange'); })
  $('.manu_list_bm_csi input').each(function(){ $(this).attr('onclick',$(this).attr('onchange')).removeAttr('onchange'); })
}
// RESET SORT FILTER STYLE
bm_sort_mfg('a');
 
$('.manu_list_bm a,.manu_list_bm_csi a').each(function(){ if ($(this).html().length > 18){ 
$(this).html($(this).html().substr(0,15)).append('...');
} 
$('.bk_num_of_prod').html($('.bm_single_result').length+' bookmark(s)');
}); 

// SHARE START 
$('.share_link').hoverIntent(function() {
trigger=$(this);
show_share(trigger);
}, function(){});


$('#share_wrapper').mouseleave(function() {
  $('#share_wrapper').addClass('hide');
      
});
// SHARE END
			} //END OF SUCCESS
			});
		
		
        
}, function () {});
    $(".bookmarks_menu").mouseleave(function () {
        setTimeout('close_bookmarks()', 1000);
    });
// BOOKMARKS MENU END ///////////////////////////////////////////////////////////////////////////////////////////////////

if ($('#cid').html()!=null  && $('#rid').html()!=null){


/* $.ajax({
  type: "POST",
  cache: false,
  url: "http://www.thebluebook.com/wsnsa.dll/WService=wsbrk1/wobidcontext.p?request=loginBBB&cntxt="+$('#cid').html()+"&crid="+$('#rid').html(),
  success: function(html){
$('#bpm_login_link').load('index.php?id=13&checkuser=true');
  }
}).done(function( msg ) {
// alert( "Data Saved: " + msg );
});
*/
}
}); 
// END OF DOCUMENT READY /////////////////////////////////////////////////////////////////////////////////////////////////////////////

// SAVE START
function show_save(trigger) {
    if ($(trigger).parent().parent().parent().attr('class') == 'more_results') {
        newshareurl = $('head base').attr('href') + $(trigger).parent().parent().find('.result_link_p .result_link').attr('href');
        newsharetitle = $(trigger).parent().prev().prev().find('a').text();
    } 
	else if ($(trigger).parent().parent().parent().parent().parent().attr('class') == 'local_supp_wrapper') {
        newshareurl = $('head base').attr('href') + $(trigger).attr('href') + '&productid=' + $('.prod_descript_wrapper div:not(".hide") div:not(.hide) span.productid').html() + '&fn=' + $(".pv_prod_img_wrapper #inp").val();
        newsharetitle = $('.prod_descript_wrapper div:not(.hide) div:not(.hide) strong').html();
    } 
	else if ($(trigger).parents('body').attr('id') == 'pv_body') {
        newshareurl =$('head base').attr('href') + $(trigger).attr('href') + '&productid=' + $('html body#pv_body center div#dialog-modal table#lbox tbody tr td.lbox_cc div#dialog_content table.lg_pv_body_wrapper tbody tr td#pv_top_content div:not(.hide) table.lg_pv_content_wrapper tbody tr td.lg_pv_description span#pv_prodid.hide').html() + '&fn=' + $(".lg_pv_fam_wrapper #inp").val();
        newsharetitle = $('head title').html();
    }
	else if ($(trigger).parent().parent().parent().parent().attr('class') == 'lbox_header') {
        newshareurl = $('head base').attr('href') + $(trigger).attr('href') + '&productid=' + $('#lbox tbody tr td.lbox_cc div#dialog_content table.lg_pv_body_wrapper tbody tr td#pv_top_content div:not(.hide) table.lg_pv_content_wrapper tbody tr td.lg_pv_description span#pv_prodid.hide').html() + '&fn=' + $(".lg_pv_fam_wrapper #inp").val();
        newsharetitle = $('.lg_pv_body_wrapper div:not(.hide) .lg_pv_prod_title').html();
    } 

	else if ($(trigger).parent().attr('class') == 'tb_save') {
        newshareurl = window.location.href;
        newsharetitle = $('head title').html();
    }
	else {
        newshareurl = $('head base').attr('href') + $('.active a.result_link').attr('href');
        newsharetitle = $(trigger).closest(".single_result").find(".result_link_p:eq(0) .result_link:eq(0)").text();
    }
    changeurl('savebtn1', 'bpmselect', newshareurl, newsharetitle, newsharetitle, 'Save the resulting page into MyBPMSelect', 'launch_bookmark();');
    changeurl('savebtn2', 'pdfmyurl', newshareurl, newsharetitle, newsharetitle, 'Save this result as a PDF', '');
    changeurl('savebtn3', 'favorites', newshareurl, newsharetitle, newsharetitle, 'Save this result as a browser favorite', '');
    changeurl('savebtn4', 'print', newshareurl, newsharetitle, newsharetitle, 'Print this result', '');
    $('#share_wrapper').addClass('hide');
    $('#save_wrapper').removeClass('hide');
   
   // CHANGE SHARE LOCATION
    $("#save_wrapper").position({
        my: "left top",
        at: "left bottom",
        of: $(trigger)
    })
    $('#save_wrapper').css('z-index', '7004');
}
// SAVE END ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// SHARE START 
function show_share(trigger) {
    if ($(trigger).parent().parent().parent().attr('class') == 'more_results') {
        newshareurl = $('head base').attr('href') + $(trigger).parent().parent().find('.result_link_p .result_link').attr('href');
        newsharetitle = $(trigger).parent().prev().prev().find('a').text();
    } else if ($(trigger).parent().parent().parent().parent().parent().attr('class') == 'local_supp_wrapper') {
        newshareurl = $('head base').attr('href') + $(trigger).attr('href') + '&productid=' + $('.prod_descript_wrapper div:not(".hide") div:not(".hide") span.productid').html() + '&fn=' + $(".pv_prod_img_wrapper #inp").val();
        newsharetitle = $('.prod_descript_wrapper div:not(".hide") div:not(".hide") strong').html();
    }
		else if ($(trigger).parents('body').attr('id') == 'pv_body') {
        newshareurl =$('head base').attr('href') + $(trigger).attr('href') + '&productid=' + $('#pv_top_content > div:not(".hide") .lg_pv_description #pv_prodid').html() + '&fn=' + $(".lg_pv_fam_wrapper #inp").val();
        newsharetitle = $('head title').html();
    }
	else if ($(trigger).parent().parent().parent().parent().attr('class') == 'lbox_header') {
        newshareurl = $('head base').attr('href') + $(trigger).attr('href') + '&productid=' + $('#lbox tbody tr td.lbox_cc div#dialog_content table.lg_pv_body_wrapper tbody tr td#pv_top_content div:not(.hide) table.lg_pv_content_wrapper tbody tr td.lg_pv_description span#pv_prodid.hide').html() + '&fn=' + $(".lg_pv_fam_wrapper #inp").val();
        newsharetitle = $('.lg_pv_body_wrapper div:not(.hide) .lg_pv_prod_title').html();
    }else if ($(trigger).parent().attr('class') == 'tb_share') {
        newshareurl = window.location.href;
        newsharetitle = $('head title').html();
    }
	else if($(trigger).attr('id')=='bm_share_link'){
	    newshareurl = $(trigger).closest('.bm_single_result.bm_active').find('#bmm_bookurl').attr('href');
        newsharetitle = $(trigger).closest('.bm_single_result.bm_active').find('.bookmark_title #bmm_pn').text();
	}
	else {
        newshareurl = $('head base').attr('href') + $('.active a.result_link').attr('href');
        newsharetitle = $(trigger).closest(".single_result").find(".result_link_p:eq(0) .result_link:eq(0)").text();
    }
    changeurl('sharebtn1', 'email', newshareurl, newsharetitle, newsharetitle, 'Send some one a link to this result via Email', '');
    changeurl('sharebtn2', 'facebook', newshareurl, newsharetitle, newsharetitle, 'Like and comment on this result via Facebook', '');
    changeurl('sharebtn3', 'twitter', newshareurl, newsharetitle, newsharetitle, 'Tweet and share this result via Twitter', '');
    changeurl('sharebtn4', 'linkedin', newshareurl, newsharetitle, newsharetitle, 'Update your profile and share this result on LinkedIn', '');
    $('#save_wrapper').addClass('hide');
    $('#share_wrapper').removeClass('hide');
    // CHANGE SHARE LOCATION
    $("#share_wrapper").position({
        my: "left top",
        at: "left bottom",
        of: $(trigger)
    })
    $('#share_wrapper').css('z-index', '7773');
}
// SHARE END ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// CHANGE URL FOR SHARE / SAVE START
function changeurl(placeholder, service, url, title, description, urllabel, launch) {

    defaulturl = 'http://www.addthis.com/bookmark.php?v=250&pubid=ra-4e6f5fd9299036b1';
    if (service != 'bpmselect') {
        $("#" + placeholder + " a").remove();
        $("#" + placeholder).append('<a href="' + defaulturl + '" class="addthis_button_' + service + '" addthis:url="' + url + '" addthis:title="' + title + '" addthis:description="' + description + '" onclick="' + launch + ' return false;"><span class="at300bs at15nc at15t_' + service + '" onclick="' + launch + ' return false;"></span></a>');
        $("#" + placeholder).next().find("a").remove();
        $("#" + placeholder).next().html('<a href="' + defaulturl + '" class="addthis_button_' + service + ' remove_img at300b" addthis:url="' + url + '" addthis:title="' + title + '" addthis:description="' + description + '" onclick="' + launch + ' return false;"><span class="at300bs at15nc at15t_' + service + '" onclick="' + launch + ' return false;"></span>' + urllabel + '</a>');
        //$('.at15t_print').attr('onclick', 'launch_print(\'' + url + '\');');
		//$('.addthis_button_print.remove_img').attr({'href':url,'onclick':'return true'}).removeAttr('class');
		//$('.addthis_button_print').attr({'href':url,'onclick':'return true'});
		//$('.addthis_button_print .at15t_print').remove();
	
		$('#savebtn4').parent().attr('onclick','launch_print(\'' + url + '\');');
		//$('#savebtn4').parent().attr('onclick','window.location.href=\''+url+'#bpmprint=true\'');
		
		//$('#savebtn4 a,.addthis_button_print.remove_img').removeClass('addthis_button_print').attr({'onclick':$('#savebtn4').parent().attr('onclick'),'href':url+'#bpmprint=true'});
		if ($('#savebtn2 a').length >0){
		if ($('#savebtn2 a').attr('addthis:url').length > 82){
		$('#savebtn2 a').attr('addthis:url',$('#savebtn2 a').attr('addthis:url').substr(0,82));
		$('.addthis_button_pdfmyurl').attr('addthis:url',$('#savebtn2 a').attr('addthis:url'));
		}
		}


		
		
        //RE-INIT ADD THIS JS
        var script = 'http://s7.addthis.com/js/250/addthis_widget.js#username=ra-4e6f5fd9299036b1&domready=1';
        if (window.addthis) {
            window.addthis = null;

        }
        $.getScript(script);
		
        // END OF ADD THIS INIT 

    } else {
        $("#" + placeholder).html('<a onclick="launch_bookmark(); hide_save(); return false;" addthis:description="' + description + '" addthis:title="' + title + '" addthis:url="' + url + '" class="' + service + '_button" href="' + url + '" title="' + title + '"><img src="assets/images/bpm_ico.png" /></a>');
        $("#" + placeholder).next().find("a").attr('onclick', 'launch_bookmark(); hide_save(); return false;');
    }
}
// CHANGE URL FOR SHARE / SAVE END //////////////////////////////////////////////////////////////////////////////////////////////////

// HIDE SAVE FOR BPM BOOKMARK CLICK START 
function hide_save() {
    $('#save_wrapper').addClass('hide');
}
// HIDE SAVE FOR BPM BOOKMARK CLICK END /////////////////////////////////////////////////////////////////////////////////////////////

//LAUNCH BOOKMARK ADD/EDIT START 
function launch_bookmark(loc) {
if (loc=='notes'){
trigger=$('html body.int_body div.ui-dialog div#dialog-modal.ui-dialog-content table#lbox tbody tr td.lbox_cc div#dialog_content table.lbox_header tbody tr td a.more_link');
        newshareurl = $('head base').attr('href') + $(trigger).attr('href') + '&productid=' + $('#lbox tbody tr td.lbox_cc div#dialog_content table.lg_pv_body_wrapper tbody tr td#pv_top_content div:not(.hide) table.lg_pv_content_wrapper tbody tr td.lg_pv_description span#pv_prodid.hide').html() + '&fn=' + $(".lg_pv_fam_wrapper #inp").val();
        newsharetitle = $('.lg_pv_body_wrapper div:not(.hide) .lg_pv_prod_title').html();
}
    $("#dialog-modal-bookmarks").dialog({
        resizable: false,
        width: 575,
        modal: true,
        autosize: true,
        position: 'center top'

    });
    $('.ui-dialog-titlebar').remove();
    $('.lbox_cc').css('width', $('#dialog-modal-bookmarks').width() - 12);


        $.ajax({
            url: 'index.php?id=9&user=' + $(this).parent().attr('id'),
            success: function (data) {
			$('#dialog_content_bookmarks').html(data);
			// BUILD BOOKMARK START 
		    if ($(trigger).parent().parent().parent().attr('class') == 'more_results') {
                $('#bookurl').val(newshareurl);
		        $('#companyid').val($('#main_qv table').attr('id'));
				$('#bm_mfg').val($('.active h2').text());
				$('#imgrid').val($('.prod_descript_wrapper div:not(.hide) div:not(.hide) span.productid').html());
				$('#bm_pfn').val($('.pv_prod_img_wrapper #hp_dropdown #inp').val());
				$('#bm_pn').val(newsharetitle);
				$('#notes').val($(trigger).parent().prev().html());
				//$('#csi').val($('#hp_dropdown2 #inp').val());
				$('#csi').replaceWith('<select name="csi" id="csi" class="bookmark_inp"><option value="'+$('#hp_dropdown2 #inp').val()+'">'+$('#hp_dropdown2 #inp').val()+'</option>'+csilist+'</select>');
				$('.bpm_prod_img').html($('.pv_prod_img_wrapper div div div:not(.hide) div:not(.hide) a').html());
				$('#thumb').val($('.pv_prod_img_wrapper div div div:not(.hide) div:not(.hide) a').html());
	   
    } else if ($(trigger).parent().parent().parent().parent().parent().attr('class') == 'local_supp_wrapper') {
			    $('#bookurl').val(newshareurl);
				$('#companyid').val($('#main_qv table').attr('id'));
				$('#bm_mfg').val($('.active h2').text());
				$('#imgrid').val($('.prod_descript_wrapper div:not(.hide) div:not(.hide) span.productid').html());
				$('#bm_pfn').val($('.pv_prod_img_wrapper #hp_dropdown #inp').val());
				$('#bm_pn').val($('.prod_descript_wrapper div:not(.hide) div:not(.hide) strong').html());
				$('#notes').val($('.prod_descript_wrapper div:not(.hide) div:not(.hide) .prod_title_descript').html());
				//$('#csi').val($('#hp_dropdown2 #inp').val());
				$('#csi').replaceWith('<select name="csi" id="csi" class="bookmark_inp"><option value="'+$('#hp_dropdown2 #inp').val()+'">'+$('#hp_dropdown2 #inp').val()+'</option>'+csilist+'</select>');
				$('.bpm_prod_img').html($('.pv_prod_img_wrapper div div div:not(.hide) div:not(.hide) a').html());
				$('#thumb').val($('.pv_prod_img_wrapper div div div:not(.hide) div:not(.hide) a').html());
    } 
	else if ($(trigger).parents('body').attr('id') == 'pv_body') {
                $('#bookurl').val(newshareurl);
				$('#companyid').val($('#compid').text());
				$('#bm_mfg').val($('#pvcompname').text());
				$('#imgrid').val($('#lbox tbody tr td.lbox_cc div#dialog_content table.lg_pv_body_wrapper tbody tr td#pv_top_content div:not(.hide) table.lg_pv_content_wrapper tbody tr td.lg_pv_description span#pv_prodid.hide').html());
				$('#bm_pfn').val($(".lg_pv_fam_wrapper #inp").val());
				$('#bm_pn').val(newsharetitle);
				$('#notes').val($('#lbox tbody tr td.lbox_cc div#dialog_content table.lg_pv_body_wrapper tbody tr td#pv_top_content div:not(.hide) table.lg_pv_content_wrapper tbody tr td.lg_pv_description #notes').text());
				//$('#csi').val($('#hp_dropdown2 #inp').val());
				$('#csi').replaceWith('<select name="csi" id="csi" class="bookmark_inp"><option value="'+$('#hp_dropdown2 #inp').val()+'">'+$('#hp_dropdown2 #inp').val()+'</option>'+csilist+'</select>');
				$('.bpm_prod_img').html($('#lbox tbody tr td.lbox_cc div#dialog_content table.lg_pv_body_wrapper tbody tr td#pv_top_content div:not(.hide) table.lg_pv_content_wrapper tbody tr td.lg_pv_img_wrapper div').html());
				$('#thumb').val($('#lbox tbody tr td.lbox_cc div#dialog_content table.lg_pv_body_wrapper tbody tr td#pv_top_content div:not(.hide) table.lg_pv_content_wrapper tbody tr td.lg_pv_img_wrapper div').html());
    } 
	
	else if ($(trigger).parent().parent().parent().parent().attr('class') == 'lbox_header') {
             	$('#bookurl').val(newshareurl);
				$('#companyid').val($('#compid').text());
				$('#bm_mfg').val($('#pvcompname').text());
				$('#imgrid').val($('#lbox tbody tr td.lbox_cc div#dialog_content table.lg_pv_body_wrapper tbody tr td#pv_top_content div:not(.hide) table.lg_pv_content_wrapper tbody tr td.lg_pv_description span#pv_prodid.hide').html());
				$('#bm_pfn').val($(".lg_pv_fam_wrapper #inp").val());
				$('#bm_pn').val(newsharetitle);
				//alert ($('#lbox tbody tr td.lbox_cc div#dialog_content table.lg_pv_body_wrapper tbody tr td#pv_top_content div:not(.hide) table.lg_pv_content_wrapper tbody tr td.lg_pv_description span#notes').html());
				$('#dialog-modal-bookmarks.ui-dialog-content table#lbox tbody tr td.lbox_cc div#dialog_content_bookmarks div#addbookmarkwrapper table tbody tr td table tbody tr td.add_bm_col2 form#bpm_new_bookmark_frm textarea#notes.bookmark_inp').val($('#lbox tbody tr td.lbox_cc div#dialog_content table.lg_pv_body_wrapper tbody tr td#pv_top_content div:not(.hide) table.lg_pv_content_wrapper tbody tr td.lg_pv_description span#notes').html());
				//$('#csi').val($('#hp_dropdown2 #inp').val());
				if ($('#hp_dropdown2 #inp').val()=='undefined'){
				$('#csi').replaceWith('<select name="csi" id="csi" class="bookmark_inp">'+csilist+'</select>');
}else {
				$('#csi').replaceWith('<select name="csi" id="csi" class="bookmark_inp"><option value="'+$('#hp_dropdown2 #inp').val()+'">'+$('#hp_dropdown2 #inp').val()+'</option>'+csilist+'</select>');

}
				$('.bpm_prod_img').html($('#lbox tbody tr td.lbox_cc div#dialog_content table.lg_pv_body_wrapper tbody tr td#pv_top_content div:not(.hide) table.lg_pv_content_wrapper tbody tr td.lg_pv_img_wrapper div').html());
				$('#thumb').val($('#lbox tbody tr td.lbox_cc div#dialog_content table.lg_pv_body_wrapper tbody tr td#pv_top_content div:not(.hide) table.lg_pv_content_wrapper tbody tr td.lg_pv_img_wrapper div').html());
			
    } else if ($(trigger).parent().attr('class') == 'tb_save') {
	var tbdetails = $('head meta[name=keywords]').attr("content").split("|");
	
				$('#bookurl').val(newshareurl);
				$('#companyid').val($('#toolbar_iframe').attr('class'));
				$('#bm_mfg').val(tbdetails[0]);
				$('#imgrid').val(null);
				$('#bm_pfn').val(null);
				$('#bm_pn').val($('#toolbar_iframe').attr('src'));
				$('#notes').val($('head meta[name=description]').attr("content"));
				//$('#csi').val(tbdetails[1]);
				$('#csi').replaceWith('<select name="csi" id="csi" class="bookmark_inp">'+csilist+'</select>');
				$('.bpm_prod_img').html('<img src="'+$('head meta[property="og:image"]').attr("content")+'" />');
				$('#thumb').val('<img src="'+$('head meta[property="og:image"]').attr("content")+'" />');
    } else {
                $('#bookurl').val(newshareurl);
		        $('#companyid').val($(trigger).closest('.single_result').parent().attr('id'));
				$('#bm_mfg').val($('.active h2').text());
				$('#imgrid').val($('.prod_descript_wrapper div:not(.hide) div:not(.hide) span.productid').html());
				$('#bm_pfn').val($('.pv_prod_img_wrapper #hp_dropdown #inp').val());
				$('#bm_pn').val(newsharetitle);
				$('#notes').val($(trigger).parent().parent().parent().parent().prev().html());
				//$('#csi').val($('#hp_dropdown2 #inp').val());
				$('#csi').replaceWith('<select name="csi" id="csi" class="bookmark_inp"><option value="'+$('#hp_dropdown2 #inp').val()+'">'+$('#hp_dropdown2 #inp').val()+'</option>'+csilist+'</select>');
				$('.bpm_prod_img').html($('.pv_prod_img_wrapper div div div:not(.hide) div:not(.hide) a').html());
				$('#thumb').val($('.pv_prod_img_wrapper div div div:not(".hide") div:not(.hide) a').html());
    }
			// BUILD BOOKMARK END
			$( ".bpm_prod_img img" ).aeImageResize({ height: 140, width: 140 });
			}
			});
			
			}
			

////////// CSI LIST START ////
var csilist='<option value="Unassigned">Unassigned</option>\n<option value="010000 General Requirements">010000 General Requirements</option>\n<option value="020000 Existing Conditions">020000 Existing Conditions</option>\n<option value="030000 Concrete">030000 Concrete</option>\n<option value="040000 Masonry">040000 Masonry</option>\n<option value="050000 Metals">050000 Metals</option>\n<option value="060000 Wood">060000 Wood</option>\n<option value="070000 Thermal and Moisture Protection">070000 Thermal and Moisture Protection</option>\n<option value="080000 Openings">080000 Openings</option>\n<option value="090000 Finishes">090000 Finishes</option>\n<option value="100000 Specialties">100000 Specialties</option>\n<option value="110000 Equipment">110000 Equipment</option>\n<option value="120000 Furnishings">120000 Furnishings</option>\n<option value="130000 Special Construction">130000 Special Construction</option>\n<option value="140000 Conveying Equipment">140000 Conveying Equipment</option>\n<option value="210000 Fire Suppression">210000 Fire Suppression</option>\n<option value="220000 Plumbing">220000 Plumbing</option>\n<option value="230000 Heating">230000 Heating</option>\n<option value="250000 Integrated Automation">250000 Integrated Automation</option>\n<option value="260000 Electrical">260000 Electrical</option>\n<option value="270000 Communications">270000 Communications</option>\n<option value="280000 Electronic Safety and Security">280000 Electronic Safety and Security</option>\n<option value="310000 Earthwork">310000 Earthwork</option>\n<option value="320000 Exterior Improvements">320000 Exterior Improvements</option>\n<option value="330000 Utilities">330000 Utilities</option>\n<option value="340000 Transportation">340000 Transportation</option>\n<option value="350000 Waterway and Marine Construction">350000 Waterway and Marine Construction</option>\n<option value="400000 Process Integration">400000 Process Integration</option>\n<option value="410000 Material Processing and Handling Equipment">410000 Material Processing and Handling Equipment</option>\n<option value="420000 Process Heating">420000 Process Heating</option>\n<option value="430000 Process Gas and Liquid Handling">430000 Process Gas and Liquid Handling</option>\n<option value="440000 Pollution Control Equipment">440000 Pollution Control Equipment</option>\n<option value="450000 Industry-Specific Manufacturing Equipment">450000 Industry-Specific Manufacturing Equipment</option>\n';


////////// CSI LIST END //////
//LAUNCH BOOKMARK ADD/EDIT END ////////////////////////////////////////////////////////////////////////////////////////////////////

//LAUNCH BOOKMARK EDIT START 
function launch_edit_bookmark() {
    $("#dialog-modal-bookmarks").dialog({
        resizable: false,
        width: 575,
        modal: true,
        autosize: true,
        position: 'center top'

    });
    $('.ui-dialog-titlebar').remove();
    $('.lbox_cc').css('width', $('#dialog-modal-bookmarks').width() - 12);
	
        $.ajax({
            url: 'index.php?id=14&user=' + $(this).parent().attr('id'),
            success: function (data) {
			$('#dialog_content_bookmarks').html(data);
			
			    $('#bookid').val($('.bm_active #bmm_bookid').html());
				$('#bookurl').val($('.bm_active #bmm_bookurl').html());
				$('#companyid').val($('.bm_active').attr('id'));
				$('#bm_mfg').val($('.bm_active #bmm_compname').html());
				$('#imgrid').val($('.bm_active #bmm_imgrid').html());
				$('#bm_pfn').val($('.bm_active #bmm_pfn').html());
				$('#bm_pn').val($('.bm_active #bmm_pn').html());
				$('#notes').val($('.bm_active #bmm_notes').html());
				//$('#csi').val($('.bm_active #bmm_csi').html());
				$('#csi').replaceWith('<select name="csi" id="csi" class="bookmark_inp"><option value="'+$('.bm_active #bmm_csi').html()+'">'+$('.bm_active #bmm_csi').html()+'</option>'+csilist+'</select>');
				$('.bpm_prod_img').html($('.bm_active #bmm_img').html());
				$('#thumb').val($('.bm_active #bmm_img').html());
				//$('#thumb').val('Thumbnail text');
				//$.getScript('assets/js/common.js');
			}
			});

}
//LAUNCH BOOKMARK EDIT END ////////////////////////////////////////////////////////////////////////////////////////////////////



// OPEN WINDOW AND SHOW PRINT DIALOG START
function launch_print(loc){
    window.location.href=loc+'#bpmprint=true';
	//window.open(loc+'#bpmprint=true','_blank');

}
// OPEN WINDOW AND SHOW PRINT DIALOG START //////////////////////////////////////////////////////////////////////////////////////////

//END SHARE AND SAVE FUNCTIONALITY //////////////////////////////////////////////////////////////////////////////////////////////////

// MODAL LOADER START
function show_loader() {
    $("#dialog-modal").dialog({
        width: 870,
        resizable: false,
        modal: true,
        autosize: true
    });
    $('.ui-dialog-titlebar').remove();
    $('.lbox_cc').css('width', $('#dialog-modal').width() - 12);
    $('#dialog_content').html('<p style="text-align:center;"><img src="assets/images/ajax-loader.gif"><h2 style="text-align:center;">Loading results...</h2></p>');
}
// MODAL LOADER END //////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// CLOSE DIALOG ON X BTN CLICK
function lbox_close() {
    $('#dialog-modal').dialog('close');
}
function lbox_close_request() {
    $('#dialog-modal-request').dialog('close');
}
function lbox_close_bookmarks() {
    $('#dialog-modal-bookmarks').dialog('close');
}
function close_bookmarks() {
     $('.bookmarks_menu').removeAttr('style');
}
    // CLOSE DIALOG ON OVERLAY CLICK
    $('.ui-widget-overlay').live('click', function () {
        $('#dialog-modal').dialog('close');
        $('#dialog-modal-request').dialog('close');
		$('#dialog-modal-bookmarks').dialog('close');
    });

// LAUNCH LOGIN START
function launch_login() {
    $("#dialog-modal").dialog({
        resizable: false,
        width: 575,
        modal: true,
        autosize: true,
        position: 'center top'
    });
    $('.ui-dialog-titlebar').remove();
    $('.lbox_cc').css('width', $('#dialog-modal').width() - 12);
    $('#dialog_content').load('index.php?id=5');
    $('#dialog-modal').css("margin-top", "100px");
}
// LAUNCH LOGIN START ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// LAUNCH REGISTRATION PROCESS START
function launch_register() {
    $("#dialog-modal").dialog({
        resizable: false,
        width: 750,
        modal: true,
        autosize: true,
        position: 'center top'

    });
    $('.ui-dialog-titlebar').remove();
    $('.lbox_cc').css('width', $('#dialog-modal').width() - 12);
    $('#dialog_content').load('index.php?id=8');
    $('#dialog-modal').css("margin-top", "100px")
}
// LAUNCH REGISTRATION PROCESS END ///////////////////////////////////////////////////////////////////////////////////////////////////



// SEARCH FORM CHECK START
 function form_check(loader) {
 $('#bpm #greenquery,##bpm #as_sitesearch').remove();
 if ($('#pageid').val()!='2'){
 if ($('#srch').val()=='Enter Search Term' || $('#srch').val()==''){
 alert ('Please Enter a Search Term.');
  return false;
 }else {
 document.bpm.submit();
 if (loader!='noloader'){
 show_loader();
 }
 }
 }else {
     if ($('#srch').val() == 'Enter Search Term' || $('#srch').val() == '' && $('#inp').val() == 'Browse by CSI Classification') {
         alert('Please Enter a Search Term.');
         return false;
     } else {
         document.bpm.submit();
         if (loader!='noloader'){
 show_loader();
 }
     }
	}
 }

 // SEARCH FORM CHECK END ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 // LAUNCH REQUEST MODAL START 
function launch_request(url) {
    $("#dialog-modal-request").dialog({
        width: 660,
        resizable: false,
        modal: true,
        autosize: true
    });
	if ($('#dialog-modal-request .launched').length==0){
	$('#dialog-modal-request .lbox_cc').addClass('launched');
	//$('.ui-dialog').css('top','40px');
		$( "#dialog-modal-request").parent().position({
				of: $(window),
				my: 'center top',
				at: 'center top'
			});
	}
    $('.ui-dialog-titlebar').remove();
    $('.ui-dialog-titlebar').remove();
    $('.lbox_cc').css('width', $('#dialog-modal').width() - 12);
    $('#dialog_content_request').html('<p style="text-align:center;"><img src="assets/images/ajax-loader.gif"><h2 style="text-align:center;">Loading results...</h2></p>');
    $('#dialog_content_request').html('<table class="lbox_header"><tbody><tr><td align="left"></td><td align="right">&nbsp;&nbsp;&nbsp;</td><td align="right"><img border="0" align="right" onclick="lbox_close_request();" id="pv_close_btn" src="assets/images/lbox_close_btn.png"></td></tr></tbody></table><iframe src="' + url + '" frameborder="0" style="width:620px; height:640px;"></iframe>');
}
 // LAUNCH REQUEST MODAL END /////////////////////////////////////////////////////////////////////////////////////////////////// 
 
 
 // TOGGLE LOCAL SUPPLIERS AND IMAGE GALLERY FOR PROVIEW  START ////////////////////////////////////////////////////////////////
 function toggle_subs(toggle){
  if (toggle=='subs'){
  $('#pv_top_content').addClass('hide');
  $('#show_subs_link').addClass('hide');
  $('#pv_subs_content').removeClass('hide');
  }else if (toggle=='link') {
  $('#pv_subs_content_lower').removeClass('hide');
  $('#show_subs_link').attr('onclick', 'toggle_subs(\'content\'); return false;').html('Click here to hide local subs and suppliers &raquo;');
  }
  else if (toggle=='content') {
  $('#pv_subs_content_lower').addClass('hide');
  $('#show_subs_link').attr('onclick', 'toggle_subs(\'link\'); return false;').html('Click here to view local subs and suppliers &raquo;');
  }
  else {
  $('#pv_top_content').removeClass('hide');
  $('#show_subs_link').removeClass('hide');
  $('#pv_subs_content').addClass('hide');
  }
  
  }
 // TOGGLE LOCAL SUPPLIERS AND IMAGE GALLERY FOR PROVIEW  START ////////////////////////////////////////////////////////////////
 
 // LAUNCH LOCAL SUPPLIER DIALOG START //////////////////////////
 function launch_local_sub(url){
    $("#dialog-modal-request").dialog({
        width: 1020,
        resizable: false,
        modal: true,
        autosize: true
    });
	if ($('#dialog-modal-request .launched').length==0){
	$('#dialog-modal-request .lbox_cc').addClass('launched');
	//$('.ui-dialog').css('top','40px');
		$( ".ui-dialog" ).position({
				of: $(window),
				my: 'center top',
				at: 'center top'
			});
	}

	var prevurl;
	var nexturl;
	prevurl=$('a[href="'+url+'"]').parent().parent().prev('tr').find('a').attr('href');
	nexturl=$('a[href="'+url+'"]').parent().parent().next('tr').find('a').attr('href');
	if (prevurl.length==0 || prevurl=='#' || prevurl==''){
	prevurlfull='';
	}
	else {
	prevurlfull='<a href="'+prevurl+'" onclick="launch_local_sub(\''+prevurl+'\'); return false;"><< PREVIOUS</a>';
	}
	
		if (nexturl.length==0 || nexturl=='#' || nexturl==''){
	nexturlfull='';
	}
	else {
	nexturlfull='<a href="'+nexturl+'" onclick="launch_local_sub(\''+nexturl+'\'); return false;">NEXT >></a>';
	}
	
    $('.ui-dialog-titlebar').remove();
    $('.ui-dialog-titlebar').remove();
    $('#dialog-modal-request .lbox_cc').css({'width':$('#dialog-modal').width() - 12,'background':'url(assets/images/ajax-loader.gif) no-repeat center center #ffffff'});
    $('#dialog_content_request').html('<p style="text-align:center;"><img src="assets/images/ajax-loader.gif"><h2 style="text-align:center;">Loading results...</h2></p>');
    $('#dialog_content_request').html('<table class="lbox_header"><tbody><tr><td align="center" style="font-weight:bold;">'+prevurlfull+'&nbsp;&nbsp;&nbsp;&nbsp;'+nexturlfull+'<img border="0" align="right" onclick="lbox_close_request();" id="pv_close_btn" src="assets/images/lbox_close_btn.png"></td></tr></tbody></table><iframe src="' + url + '" frameborder="0" style="width:980px; height:610px;"></iframe>');
}

 // LAUNCH LOCAL SUPPLIER DIALOG END //////////////////////////
 
 // BPM LOGIN SUBMIT START ///////////////////////////////////
 function bpm_login_submit(){
 $.ajax({
  type: "POST",
  url: "/wsnsa.dll/WService=wsbrk1/mfgsearch/bpmselect_login.p?request=login",
  data: $('#bpmlogin').serialize(),
  success: function(html){
  var mySplitResult = html.split("|");
  //alert (mySplitResult[0]);
if (mySplitResult[0]==0) {
alert ('Incorrect userid or password');
}else if(mySplitResult[0]==1){
 $('#user_drop_down_tr').removeClass('hide');
   $('#user_drop_down').html(mySplitResult[1]);
   $('#request').val('login2');
   }else if (mySplitResult[0].length > 2 && mySplitResult[0]!=1  && mySplitResult[0]!=0){
$('body').after('<iframe style="width:1px; height:1px;" id="loginiframe" src="http://www.thebluebook.com/wsnsa.dll/WService=wsbrk1/wobidcontext.p?request=loginBBB&cntxt='+mySplitResult[0]+'&crid='+mySplitResult[1]+'&rdrURL='+encodeURIComponent("http://www.thebluebook.com/bpm/blank2.htm")+'"></iframe>');
 location.reload(true);
   }

  }
}).done(function( msg ) {
 // alert( "Data Saved: " + msg );
});
}
 // BPM LOGIN SUBMIT END ///////////////////////////////////
 
  // BPM LOGOUT SUBMIT START ///////////////////////////////////
 function bpm_logout_submit(){

 // $('body').after('<iframe style="width:1px; height:1px;" src="http://www.thebluebook.com/wsnsa.dll/WService=wsbrk1/wobidcontext.p?request=logoutBBB&cntxt='+$('#cid').html()+'&crid='+$('#rid').html()+'&rdrURL='+encodeURIComponent("http://www.thebluebook.com/bpm/blank2.htm")+'"></iframe>');
 //document.cookie  = 'ContextID=logoff; PATH=/ expires=Fri, 31 Dec 1999 23:59:59 GMT; ';
 document.cookie = "ContextID" + "=; expires=Fri, 31 Dec 1999 23:59:59 GMT; path=/";
 location.reload(true);
 //document.cookie ='ContextID=ShukkhmkwGpQcdlO; expires=Thu, 2 Aug 2001 20:47:11 UTC;';
 
 //setCookie('ContextID','logoff');
 //deleteCookie('ContextID','/');
 //deleteCookie('ContextID', '.');
 //alert (getCookie('ContextID'));
 
//eraseCookie('ContextID');
 
 //alert ('deleted '+ document.cookie);
 
 // setTimeout('location.reload(true)', 1000);
/* $.ajax({
  type: "POST",
  url: "wsnsa.dll/WService=wsbrk1/mfgsearch/bpmselect_login.p?request=logout",
  success: function(html){

  }
}).done(function( msg ) {
 // alert( "Data Saved: " + msg );
});
*/

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

}
function deleteCookie(name,path,domain) {
alert ('1');
if (getCookie(name)) {
document.cookie = name + "=" + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
alert('2');
}

function getCookie (name) {
alert ('getcookie');
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg)
return getCookieVal (j)
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}

function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}

function setCookie (pcName, pcValue, pdExpire, pcPath, pcDomain, plSecure) {
document.cookie = pcName + "=" + escape(pcValue) +
((pdExpire) ? "; expires=" + pdExpire.toGMTString() : "") +
((pcPath) ? "; path=" + pcPath : "" ) +
((pcDomain) ? "; domain=" + pcDomain : "") +
((plSecure) ? "; secure" : "");
}
 // BPM LOGOUT SUBMIT END ///////////////////////////////////
 
   // BPM NEW USER LOGOUT SUBMIT START ///////////////////////////////////
 function bpm_new_user(){
 error='';
 if(!ValidateName(document.bpmnewuser.fname.value))
        error+="First Name\n";
       if(!ValidateName(document.bpmnewuser.lname.value))
        error+="Last Name\n";
   if(document.bpmnewuser.cname.value=="")
        error+="Company Name\n";
		   if(document.bpmnewuser.address.value=="")
        error+="Address 1\n";
		   if(document.bpmnewuser.city.value=="")
        error+="City\n";
		   if(document.bpmnewuser.state.value=="")
        error+="State\n";
		   if(document.bpmnewuser.zip.value=="")
        error+="Zip\n";
if(!ValidatePhone(document.bpmnewuser.phone.value))
        error+="Phone\n";
		if(!ValidatePhone(document.bpmnewuser.fax.value))
        error+="Fax\n";

    if(!ValidateEmail(document.bpmnewuser.email.value))
        error+="Email\n";
   if(document.bpmnewuser.question.value=="")
        error+="Question\n";
   if(document.bpmnewuser.password.value=="")
        error+="Password\n";


    if(error!=""){
        alert("Error! Please check:\n"+error);
		}
    else{

 $.ajax({
  type: "POST",
  url: "wsnsa.dll/WService=wsbrk1/mfgsearch/bpmselect_login.p?request=register",
  data: $('#bpmnewuser').serialize(),
  success: function(html){
  if (html==1){
  alert (' New User Created');
  location.reload(true);
  }else {
  alert ('error');
  }
  }
}).done(function( msg ) {
 // alert( "Data Saved: " + msg );
});
}
}
 // BPM NEW USER LOGOUT SUBMIT END ///////////////////////////////////
 
 // BBBID LOGIN

 function bpm_bbbid_login(){
/*if (contextId!='' && rowId!=''){ 
 $.ajax({
  type: "POST",
  url: "/wsnsa.dll/WService=wsbrk1/wobidcontext.p?request=loginBBB&cntxt="+$('#cid').html()+"&crid="+$('#rid').html(),
  success: function(html){
$('#bpm_login_link').load('index.php?id=13&checkuser=true');
  }
}).done(function( msg ) {
// alert( "Data Saved: " + msg );
});
}*/
 }

  function bpm_bbbid_logout(){
 //$.post("http://www.thebluebook.com/wsnsa.dll/WService=wsbrk1/wobidcontext.p?request=logoutBBB&cntxt="+$('#cid').html()+"&crid="+$('#rid').html()+"&rdrURL=#");
 $('body').after('<iframe src="http://www.thebluebook.com/wsnsa.dll/WService=wsbrk1/wobidcontext.p?request=logoutBBB&cntxt='+$('#cid').html()+'&crid='+$('#rid').html()+'&rdrURL='+encodeURIComponent("http://www.thebluebook.com/bpm/blank2.htm")+'"></iframe>');
 }
 // BBBID LOGIN END
 // SAVE NEW BOOKMARK //////////////////////////////////////////
 function bpm_new_bookmark(){
    $.ajax({
  type: "POST",
  url: "/wsnsa.dll/WService=wsbrk1/mfgsearch/bpmjson.p",
  data: $('#bpm_new_bookmark_frm').serialize(),
   success: function(html){
    //location.reload(true);
	//alert( "Data Saved: " + $('#bpm_new_bookmark_frm').serialize() );
	
  }
}).done(function( msg ) {
 $('#addbookmarkwrapper').html('<p><h2 style="text-align:center;">The bookmark has been saved.</h2></p>');
});
   
}
 // SAVE NEW BOOKMARK END /////////////////////////////////////
 
 //LAUNCH BOOKMARK DELETE START ////////////////////////////////////////////////////////////////////////////////////////////////////
function bpm_delete_bookmark(){
var answer = confirm("Are you sure you want to delete this bookmark?")
	if (answer){
		$('#bpm_new_bookmark_frm #action').val('d');
  $.ajax({
  type: "POST",
  url: "/wsnsa.dll/WService=wsbrk1/mfgsearch/bpmjson.p",
  data: $('#bpm_new_bookmark_frm').serialize(),
   success: function(html){
    //location.reload(true);
	//alert( "Data Saved: " + $('#bpm_new_bookmark_frm').serialize() );
  }
}).done(function( msg ) {
 $('#addbookmarkwrapper').html('<p><h2 style="text-align:center;">The bookmark has been deleted.</h2></p>');
});
	}
	else{
		alert ('not deleted');
	}


}
//LAUNCH BOOKMARK DELETE END ////////////////////////////////////////////////////////////////////////////////////////////////////

 
 // HIDE BOOKMARKS BY MFG START /////////////////////////////////////
 function filter_bm_mfg(mfg){
 $('.bm_single_result').each(function(){
if ($(this).attr('id')==mfg) {
if ($(this).is(':visible')){ $(this).addClass('hide'); }
 else { $(this).removeClass('hide') }
 
 }
 })
 }
 
  function filter_bm_csi(csi){
 $('#bookmark_wrapper div.'+csi).each(function(){
if ($(this).is(':visible')){ $(this).addClass('hide'); }
 else { $(this).removeClass('hide') }
 
 })
 }
 // HIDE BOOKMARKS BY MFG START /////////////////////////////////////
 
 // FORM CHECK START 
 function ValidateEmail(theinput){
    var s=theinput;
    if(s.search)
        return (s.search(new RegExp("^([-!#$%&'*+./0-9=?A-Z^_`a-z{|}~])+@([-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+\\.)+[a-zA-Z]{2,4}$","gi"))>=0);
    if(s.indexOf)
    {
        at_character=s.indexOf('@');
        if(at_character<=0 || at_character+4>s.length)
            return false;
    }
    if(s.length<6)
        return false;
    else
        return true;
}
 
/************************************************
 bool ValidateName(string input)
 Return true or false
 if the email is valid or not.
**************************************************/
function ValidateName(theinput){
    var s=theinput;
    if(s.search)
        return (s.search(new RegExp("^[^&'^`]+$","gi"))>=0);
    if(s.length<3)
        return false;
    else
        return true;
}
 
/************************************************
 bool ValidatePhone(string input)
 Return true or false
 if the phone number is valid or not.
 acepts - and + symbols
**************************************************/
function ValidatePhone(theinput){
    var s=theinput;
    if(s.search)
        return (s.search(new RegExp("[-+0-9]+","gi"))>=0);
    if(s.length<5)
        return false;
    else
        return true;
}
 

function CheckContactFrm(){
    var error="";
	


    if(!ValidateName(document.ContactFrm.fname.value))
        error+="First Name\n";
       if(!ValidateName(document.ContactFrm.lname.value))
        error+="Last Name\n";
   if(document.ContactFrm.cname.value=="")
        error+="Company Name\n";
		   if(document.ContactFrm.address1.value=="")
        error+="Address 1\n";
		   if(document.ContactFrm.city.value=="")
        error+="City\n";
		   if(document.ContactFrm.state.value=="")
        error+="State\n";
		   if(document.ContactFrm.zip.value=="")
        error+="Zip\n";
if(!ValidatePhone(document.ContactFrm.phone.value))
        error+="Phone\n";

    if(!ValidateEmail(document.ContactFrm.email.value))
        error+="Email\n";

   if(document.ContactFrm.lob.value=="")
        error+="Line of Business\n";
		
		   if(!document.ContactFrm.adinterest1.checked && !document.ContactFrm.adinterest2.checked && !document.ContactFrm.adinterest3.checked && !document.ContactFrm.adinterest4.checked && !document.ContactFrm.adinterest5.checked){
        error+="Ad Interest Type\n";
}

    if(error!="")
        alert("Error! Please check:\n"+error);
    else
        document.ContactFrm.submit();
	
    return;
}


function CheckMfgFrm(){
    var error="";
	
    if(!ValidateName(document.ContactFrm.fname.value))
        error+="First Name\n";
       if(!ValidateName(document.ContactFrm.lname.value))
        error+="Last Name\n";
   if(document.ContactFrm.cname.value=="")
        error+="Company Name\n";

if(!ValidatePhone(document.ContactFrm.phone.value))
        error+="Phone\n";

    if(!ValidateEmail(document.ContactFrm.email.value))
        error+="Email\n";

   if(document.ContactFrm.lob.value=="")
        error+="Line of Business\n";
		
		   if(document.ContactFrm.csi.value=="None")
        error+="CSI Division\n";
		
		   if(document.ContactFrm.url.value=="")
        error+="URL of Website\n";


    if(error!="")
        alert("Error! Please check:\n"+error);
    else
        document.ContactFrm.submit();
	
    return;
}
 // FORM CHECK END
 
 // BOOKMARK SORT START //////////////////////////////////////////////////////////////////////
 function bm_sort_mfg(dir){
 $('#bm_mfg_filter').attr('class','sort_filter_active');
 $('#bm_csi_filter').attr('class','sort_filter');
 $('#bm_date_filter').attr('class','sort_filter');
$('.bm_csi_header').remove();
if (dir=='z'){
$('#bm_mfg_filter').attr('onclick','bm_sort_mfg(\'a\'); return false;').html('Sort Manufacturer Alphabetically <img src="assets/images/sort_arrow_up.png" border="0" align="absmiddle" />');
$('#bookmark_wrapper>div').tsort('.bm_single_result',{attr:'sort:mfg', order:'asc'});

}else {
$('#bm_mfg_filter').attr('onclick','bm_sort_mfg(\'z\'); return false;').html('Sort Manufacturer Alphabetically <img src="assets/images/sort_arrow_down.png" border="0" align="absmiddle" />');
$('#bookmark_wrapper>div').tsort('.bm_single_result',{attr:'sort:mfg', order:'desc'});

}
}

 function bm_sort_csi(dir){
  $('#bm_mfg_filter').attr('class','sort_filter');
 $('#bm_csi_filter').attr('class','sort_filter_active');
 $('#bm_date_filter').attr('class','sort_filter');
if (dir=='z'){
$('#bm_csi_filter').attr('onclick','bm_sort_csi(\'a\'); return false;').html('Sort by CSI <img src="assets/images/sort_arrow_up.png" border="0" align="absmiddle" />');
$('#bookmark_wrapper>div').tsort('.bm_single_result',{attr:'sort:csi', order:'asc'});
add_csi_header();
}else {
$('#bm_csi_filter').attr('onclick','bm_sort_csi(\'z\'); return false;').html('Sort by CSI <img src="assets/images/sort_arrow_down.png" border="0" align="absmiddle" />');
$('#bookmark_wrapper>div').tsort('.bm_single_result',{attr:'sort:csi', order:'desc'});
add_csi_header();
}
}

function add_csi_header(){
   $('.bm_csi_header').remove();
   if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

 var arrDivClassNames = new Array();
             var arrDivClassIndexes = new Array();
             $('#bookmark_wrapper>div').each(function(index) {
			 $(this).css('padding-left','15px');
                 if(arrDivClassNames.indexOf($(this).attr('class').split(' ')[0])==-1){
                     arrDivClassNames.push($(this).attr('class').split(' ')[0]);
                     arrDivClassIndexes.push(index);
                 }
             });

             for(i=0;i<arrDivClassNames.length;i++){
    $('.'+arrDivClassNames[i]+':eq(0)').before( '<h2 class="bm_csi_header" style="margin:0px; padding:0px;">'+$('.'+arrDivClassNames[i]+':eq(0) #bmm_csi').html()+'</h2>');

} 
}

 function bm_sort_date(dir){
 $('#bm_mfg_filter').attr('class','sort_filter');
 $('#bm_csi_filter').attr('class','sort_filter');
 $('#bm_date_filter').attr('class','sort_filter_active');
if (dir=='z'){
$('#bm_date_filter').attr('onclick','bm_sort_date(\'a\'); return false;').html('Sort by Date Added <img src="assets/images/sort_arrow_up.png" border="0" align="absmiddle" />');
$('#bookmark_wrapper>div').tsort('.bm_single_result',{attr:'sort:date', order:'asc'});
add_date_header();
}else {
$('#bm_date_filter').attr('onclick','bm_sort_date(\'z\'); return false;').html('Sort by Date Added <img src="assets/images/sort_arrow_down.png" border="0" align="absmiddle" />');
$('#bookmark_wrapper>div').tsort('.bm_single_result',{attr:'sort:date', order:'desc'});
add_date_header();
}
}

function add_date_header(){
   $('.bm_csi_header').remove();
 var arrDivClassNames = new Array();
             var arrDivClassIndexes = new Array();
             $('#bookmark_wrapper>div').each(function(index) {
			 $(this).css('padding-left','15px');
                 if(arrDivClassNames.indexOf($(this).attr('class').split(' ')[2])==-1){
                     arrDivClassNames.push($(this).attr('class').split(' ')[2]);
                     arrDivClassIndexes.push(index);
                 }
             });

             for(i=0;i<arrDivClassNames.length;i++){
    $('.'+arrDivClassNames[i]+':eq(0)').before( '<h2 class="bm_csi_header" style="margin:0px; padding:0px;">'+$('.'+arrDivClassNames[i]+':eq(0) #bmm_date').html()+'</h2>');

} 
}

function bm_uncheckall(show){
if (show==0){
$('.manu_list_bm input').removeAttr('checked');
$('#bm_show_all_link').attr('onclick','bm_uncheckall(\'1\'); return false;').html('Check All');
$('.bm_single_result').each(function(){ $(this).addClass('hide'); });
}else {
$('.manu_list_bm input').attr('checked','checked');
$('#bm_show_all_link').attr('onclick','bm_uncheckall(\'0\'); return false;').html('Uncheck All');
$('.bm_single_result').each(function(){ $(this).removeClass('hide'); });
}
}

function bm_csi_uncheckall(show){
if (show==0){
$('.manu_list_bm_csi input').removeAttr('checked');
$('#bm_show_all_csi_link').attr('onclick','bm_csi_uncheckall(\'1\'); return false;').html('Check All');
$('#bookmark_wrapper > div').each(function(){ $(this).addClass('hide'); });
}else {
$('.manu_list_bm_csi input').attr('checked','checked');
$('#bm_show_all_csi_link').attr('onclick','bm_csi_uncheckall(\'0\'); return false;').html('Uncheck All');
$('#bookmark_wrapper > div').each(function(){ $(this).removeClass('hide'); });
}
}

function bm_sort_list_alpha(dir){
if (dir=='z'){
var mylist = $('.manu_list_bm');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   var compA = $(a).text().toUpperCase();
   var compB = $(b).text().toUpperCase();
   return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });
$('#bm_mfg_sort_link').html('Sort by Date Added').attr({'onclick':'bm_sort_list_alpha(\'a\'); return false;','title':'Click here to sort the manufcaturers by date added'});
}
else {
var mylist = $('.manu_list_bm');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   var compA = $(a).attr('id').toUpperCase();
   var compB = $(b).attr('id').toUpperCase();
   return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });
$('#bm_mfg_sort_link').html('Sort by A-Z').attr({'onclick':'bm_sort_list_alpha(\'z\'); return false;','title':'Click here to sort the manufacturer alphabetically'});
}
}
function bm_csi_sort_list_alpha(dir){
if (dir=='z'){
var mylist = $('.manu_list_bm_csi');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   var compA = $(a).text().toUpperCase();
   var compB = $(b).text().toUpperCase();
   return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });
$('#bm_csi_sort_link').html('Sort by Date Added').attr({'onclick':'bm_csi_sort_list_alpha(\'a\'); return false;','title':'Click here to sort the manufcaturers by date added'});
}
else {
var mylist = $('.manu_list_bm_csi');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   var compA = $(a).attr('id').toUpperCase();
   var compB = $(b).attr('id').toUpperCase();
   return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });
$('#bm_csi_sort_link').html('Sort by A-Z').attr({'onclick':'bm_csi_sort_list_alpha(\'z\'); return false;','title':'Click here to sort the manufacturer alphabetically'});
}
}

function bm_scrollto(mfg){
//$('#bookmark_wrapper').scrollTo( $('#'+mfg+':eq(0)'), 800 );
$('#bookmark_wrapper').scrollTop($('#'+mfg).offset().top);



}
 // BOOKMARK SORT END //////////////////////////////////////////////////////////////////////////
 
 function link_stats(acct,sid,label,num){
 if (sid==''){
 sid=$('#searchid').html();
 }
 if (num=='' & label=='Organics'){
num=$('#'+acct+' .more_results .res_sep').length;
 }
     $.ajax({
  type: "POST",
  url: "/wsnsa.dll/WService=wsbrk1/mfgsearch/bpmselect_json.p?json=linkstats&account="+acct+"&sid="+sid+"&linklabel="+label+"&numoflinks="+num,
   success: function(html){
	
  }
}).done(function( msg ) {

});
 }

