var pageId = '';
var sidenavOpenState = false;
var sidenavFlyoutOpenState = false;
var leftnavprodsUl;
var leftnavLi;
var sadeptUl;
var footerNavHolder;
var userAgent = navigator.userAgent.toLowerCase();
var isMsie = /msie/.test(userAgent) && !/opera/.test(userAgent);
var isMsie6 = /msie 6/.test(userAgent) && !/opera/.test(userAgent);
var isMsie7 = /msie 7/.test(userAgent) && !/opera/.test(userAgent);
var isFF2 = /firefox/.test(userAgent) &&/2\.0/.test(userAgent);

var settings = {
	tl: {radius: 5},
	tr: {radius: 5},
	bl: {radius: 5},
	br: {radius: 5},
	antiAlias: true,
	autoPad: true,
	validTags: ["div"]
}
var settings_less = {
	tl: {radius: 3},
	tr: {radius: 3},
	bl: {radius: 3},
	br: {radius: 3},
	antiAlias: true,
	autoPad: true,
	validTags: ["div"]
}
var settings_top = {
	tl: {radius: 5},
	tr: {radius: 5},
	bl: {radius: 0},
	br: {radius: 0},
	antiAlias: true,
	autoPad: true,
	validTags: ["div"]
}


$(document).ready(function() {
	setupHomePageFlag();
	setupBoxes();
	setupSideNav();

	$('#find_box').click(function(){
		document.getElementById('searchform').submit();
	});
});

function setupHomePageFlag() {
	var url = location.href;
	var start = url.indexOf('.com');
	start += 4;
	if ( (url.length-start) <= 3 ) {
		pageId = 'home';
	}
	//pageId
}

function setupSideNav() {
    leftnavprodsUl = $("#leftnavprods > ul");
    leftnavLi = $("#leftnavprods > ul > li");

    var a = $("#leftnavprods");
    leftnavprodsUl = $("#leftnavprods > ul");
    leftnavLi.hoverIntent({
        sensitivity: 1,
        interval: 0,
        over: function () {
            openFlyout($(this));
        },
        timeout: 0,
        out: function () {
            closeFlyout($(this));
        }
    });
    if ( pageId != 'home' ) {
	    $('#leftnavprods').hoverIntent({
	        sensitivity: 1,
	        interval: 0,
	        over: function () {
        		if ( isMsie ) {
					jQuery('#sadept').css('border','1px solid #ddd');
					jQuery('#sadept').css('width','222px');
					jQuery('#sadept').css('margin-left','0px');
					jQuery('#sadept').css('padding-left','0px');
					jQuery('#leftblocks .block').css('display','none');
				}
				jQuery('#sadept').css('display','block');
	        },
	        timeout: 0,
	        out: function () {
        		//alert('out');
				jQuery('#sadept').css('display','none');
        		if ( isMsie ) {
					jQuery('#leftblocks .block').css('display','block');
				}
	        }
	    });
	}

}

function openFlyout(d) {
	//alert('openFlyout');
	/*DBG*/ //addDebug('openFlyout');
    var a = $(d);
    a.addClass("selected");
    var g = a.data("flyout");
    if (!g) {
    	//alert('!g');
    	/*DBG*/ //addDebug('openFlyout !g 1');
        a.data("flyout", a.find("div.flyout"));
    	/*DBG*/ //addDebug('openFlyout !g 2');
    	g = a.data("flyout");
    }
    if (!$(g)[0]) {} else {
    	//alert('else');
    	/*DBG*/ //addDebug('openFlyout g 1');
        showFlyOut(a);
    	/*DBG*/ //addDebug('openFlyout g 2');
    }
}

function showFlyOut(g) {
	/*DBG*/ //addDebug('showFlyOut');
    sidenavFlyoutOpenState = true;
    leftnavLi.find("div.flyout").addClass("hide");
    var j = g.data("flyout");
    if (!g.data("lazyloaded")) {
    	//addDebug('showFlyOut :: lazyloaded....');
        j.find("img[src$='images/blank.gif'][name]").each(function () {
            $(this).attr("src", $(this).attr("name"));
            $(this).removeAttr("name");
        });
        g.data("lazyloaded", true);

        // Set the height of the wrapper div
	    var myheight=0;
	    g.find(".flyout ul").each(function () {
    		var curr_height = $(this).height();
    		if ( curr_height > myheight ) {
    			myheight = curr_height;
			}
	    });
	    myheight += 25;
	    /*DBG*/ //addDebug('showFlyOut -> height :: '+myheight);
	    g.find("div.flyout .flywrap").each(function () {
    		$(this).height(myheight);
    		$(this).css('height',myheight);
	    });
    }

    if (!g.data("positioninfo")) {
        var a = {
            offsetTop: g.offset().top,
            positionTop: g.position().top,
            totalHeight: g.totalHeight(),
            flyoutDivTotalHeight: j.totalHeight(),
            divitObj: j.find("span.divit")
        };
        //addDebug('showFlyOut gTh: '+g.totalHeight());
        //addDebug('showFlyOut jTh: '+j.totalHeight());
        g.data("positioninfo", a);
    } else {
        var a = g.data("positioninfo");
    }
    var d = 41;
    var c = -1;
    var h = $(window).scrollTop() - a.offsetTop + a.positionTop;
    if (h + 10 > c) {
        c = h + 10;
    }
    if (pageId != "home2" && d > c) {
        c = d + 5;
    }
    if (a.positionTop < c) {
        c = a.positionTop - 10;
    }
    if ((c + a.flyoutDivTotalHeight) < (a.totalHeight + a.positionTop + 6)) {
        c = (a.totalHeight + a.positionTop + 0) - a.flyoutDivTotalHeight;
    }
    var b = a.positionTop - c - 10 + (a.totalHeight / 2);
    a.divitObj.attr("style", "top:" + b + "px");
    j.attr("style", "top:" + c + "px").attr("class", "flyout");
    if (isMsie6 || isMsie7) {
        g.find("a.closer").attr("style", "right:5px");
    }
}


function closeFlyout(b) {
	//addDebug('closeFlyout');
    b.removeClass("selected");
    var a = b.data("flyout");
    if (a) {
        a.addClass("hide");
        sidenavFlyoutOpenState = false;
    } else {
        sidenavFlyoutOpenState = false;
    }
}




function addDebug(txt) {
	if ( jQuery('#debuglog') ) {
		var currdate = dateFormat(new Date(), "yyyy-dd-mm HH:MM:ss");
		jQuery('#debuglog').html( currdate + ' : ' + txt + '<br>' + jQuery('#debuglog').html() );
	}
}

function setupBoxes() {
	$('#search').click(function() {
		if ( $('#search').val() == 'Search our Product Catalog' ) {
			$('#search').val('');
		}
	});
}

jQuery.fn.superWidth = function ()
{
    if (isMsie6 && false)
    {
        var c = parseInt(this.css("border-left-width"));
        var b = parseInt(this.css("border-right-width"));
        var d = parseInt(this.css("padding-left"));
        var a = parseInt(this.css("padding-right"));
        c = c ? c : 0;
        b = b ? b : 0;
        d = d ? d : 0;
        a = a ? a : 0;
        return this.width() + c + b + d + a;
    }
    else {
        return this.width();
    }
};
jQuery.fn.superHeight = function ()
{
    if (isMsie6 && false) {
        return this.totalHeight();
    }
    else {
        return this.height();
    }
};
jQuery.fn.totalWidth = function ()
{
    var c = parseInt(this.css("border-left-width"));
    var b = parseInt(this.css("border-right-width"));
    var d = parseInt(this.css("padding-left"));
    var a = parseInt(this.css("padding-right"));
    c = c ? c : 0;
    b = b ? b : 0;
    d = d ? d : 0;
    a = a ? a : 0;
    return this.width() + c + b + d + a;
};
jQuery.fn.totalHeight = function ()
{
    var a = parseInt(this.css("border-top-width"));
    var b = parseInt(this.css("border-bottom-width"));
    var c = parseInt(this.css("padding-top"));
    var d = parseInt(this.css("padding-bottom"));
    a = a ? a : 0;
    b = b ? b : 0;
    c = c ? c : 0;
    d = d ? d : 0;

    //var thisht = this.height();
    //if (thisht < 50) { thisht = 500; }
    //return this.outerHeight() + a + b + c + d;
    //return thisht + a + b + c + d;
    return this.height() + a + b + c + d;
};
function printpage()
{
    window.print();
}

/// ==================================== OLD ADDED BACK =================================================================>>>>


// Change this for directory structure
var imagedir = "/simages/template/";

jQuery(document).ready(
	function() {
		jQuery('ul.jd_menu').jdMenu();

		// Apply list-toggle function to plus/minus images
		jQuery('img.listtoggle').click(
			function() {
				jQuery(this).siblings('div').find('ul').toggle();
				if(jQuery(this).attr('src').match('minus')) {
					jQuery(this).attr('src',imagedir+'/plus.gif');
				} else {
					jQuery(this).attr('src',imagedir+'/minus.gif');
				}
			}
		);
		jQuery('#sort').change(function () {
		    if(jQuery(this).val() != '') {
		        var sortval = jQuery(this).val();
		        //alert(sortval);
		        var my_href=location.href;
		        my_href = replaceQueryString(my_href, 'sort', sortval);
		        //alert(my_href);
	        	location.href=my_href;
	        	//jQuery(window.location).attr('href', my_href);

		    }
		});
		jQuery('.item_qty').change(function () {
			var qty_checked	= jQuery(this).attr('isc');
			var qty_wanted	= jQuery(this).val();
			var qty_avail	= jQuery(this).attr('isq');

			if ( qty_checked.length && qty_checked > 0 ) {
				//alert('wanted: '+qty_wanted+' avail:'+qty_avail);
				if ( parseInt(qty_wanted) > parseInt(qty_avail) ) {
				 	jQuery(this).val(qty_avail);
				 	alert('The quantity selected ('+qty_wanted+') is larger than the quantity on-hand('+qty_avail+'). We have updated the quantity.');
				}
			}
		});

		// Equalize main content area and left column
		if(jQuery('#leftblocks').height() > jQuery('#main').height()) {
			jQuery('#main').height(jQuery('#leftblocks').height()-5);
		} else {
			jQuery('#leftblocks').height(jQuery('#main').height());
		}
	}
);
/*
jQuery(window).bind('load', function() {
	jQuery('img').each(function() {
	    if((typeof this.naturalWidth != "undefined" &&
	        this.naturalWidth == 0 )
	        || this.readyState == 'uninitialized' ) {
	        jQuery(this).attr('src', '/images_products/medsi100/NIA.JPG');
	    }
	});
})
*/
function execFilterByManu() {
	myUrl = jQuery('#hiddCurrentStrippedUrl').val();
	myUrl += 'Manu-'+jQuery('#select_filter_manu').val()+'/';
	window.location.href = myUrl;
}
function execFilterByManuHome() {
	myUrl = '/m/'+jQuery('#select_filter_manu').val()+'/';
	window.location.href = myUrl;
}

function replaceQueryString(url, param, value) {
	var preURL = "";
	var postURL = "";
	var newURL = "";

	var start = url.indexOf(param+"=");
	if(start > -1) {
		var end			= url.indexOf("=", start);
		preURL			= url.substring(0,end) +"="+value;
		var startRest	= url.indexOf("&",start);
		postURL			= "";
		if(startRest > -1) {
			postURL=url.substring(startRest);
		}
	} else {
		var delimeter = "";
		preURL=url;
		if (url.indexOf("?") > 0)  delimeter = '&';
		else                       delimeter = '?';

		postURL=delimeter+param+"="+value;
	}
	newURL = preURL+postURL;

	return newURL;
}

function SortResults(sortBy)
{
    newLoc=document.location.toString();
    newLoc = newLoc.replace(/\?sort=priceLH/i,"");
    newLoc = newLoc.replace(/\?sort=priceHL/i,"");
    newLoc = newLoc.replace(/\?sort=name/i,"");
    newLoc = newLoc.replace(/&sort=priceLH/i,"");
    newLoc = newLoc.replace(/&sort=priceHL/i,"");
    newLoc = newLoc.replace(/&sort=name/i,"");
    if (newLoc.indexOf("?")!=-1)
    {
        newLoc = newLoc + "&sort="+sortBy;
    } else {
        newLoc = newLoc + "?sort="+sortBy;
    }
    document.location=newLoc;
}

