var onSubDiv = false;
var isoverview = false;
var hiddenName = "";

jQuery.noConflict();
jQuery(document).ready(function () {

	
    jQuery('#tab-set').tabs();
    //jquery lightwindow
    jQuery('.lightwindow').click(function () {
        //Get dimensions from rel tag
        var jWinDimensions = jQuery(this).attr('rel');
        var jWinWidth = 400;
        var jWinHeight = 300;
        var jWinTitle = " ";
        if (jWinDimensions != "") {
            var jWinWidthStart = jWinDimensions.indexOf("width") + 6;
            var jWinHeightStart = jWinDimensions.indexOf("height") + 7;
            var jWinWidth;
            var jWinHeightEnd;

            if (jWinWidthStart < jWinHeightStart) {
                jWinWidthEnd = jWinDimensions.indexOf(",", jWinWidthStart);
                jWinWidth = parseInt(jWinDimensions.substring(jWinWidthStart, jWinWidthEnd));
                jWinHeight = parseInt(jWinDimensions.substring(jWinHeightStart, jWinDimensions.length));

            }
            else {
                jWinWidth = parseInt(jWinDimensions.substring(jWinWidthStart, jWinDimensions.length));
                jWinHeightEnd = jWinDimensions.indexOf(",", jWinHeightStart);
                jWinHeight = parseInt(jWinDimensions.substring(jWinHeightStart, jWinHeightEnd));
            }
        }
        jQuery(this).colorbox({ iframe: true, width: jWinWidth, height: jWinHeight, rel: "nofollow" });
    });
    // opens non-modal window - no iframe
    jQuery('.nolightwindow').click(function () {
        //Get dimensions from rel tag
        var jWinDimensions = jQuery(this).attr('rel');
        var jWinWidth = 400;
        var jWinHeight = 300;
        var jWinTitle = " ";
        if (jWinDimensions != "") {
            var jWinWidthStart = jWinDimensions.indexOf("width") + 6;
            var jWinHeightStart = jWinDimensions.indexOf("height") + 7;
            var jWinWidth;
            var jWinHeightEnd;

            if (jWinWidthStart < jWinHeightStart) {
                jWinWidthEnd = jWinDimensions.indexOf(",", jWinWidthStart);
                jWinWidth = parseInt(jWinDimensions.substring(jWinWidthStart, jWinWidthEnd));
                jWinHeight = parseInt(jWinDimensions.substring(jWinHeightStart, jWinDimensions.length));

            }
            else {
                jWinWidth = parseInt(jWinDimensions.substring(jWinWidthStart, jWinDimensions.length));
                jWinHeightEnd = jWinDimensions.indexOf(",", jWinHeightStart);
                jWinHeight = parseInt(jWinDimensions.substring(jWinHeightStart, jWinHeightEnd));
            }
        }
        jQuery(this).colorbox({ iframe: false, width: jWinWidth, height: jWinHeight, rel: "nofollow" });
    });
    // tree navigation
    jQuery('.treenav').find('li').each(function () {
        if (jQuery(this).children('ul').length > 0) {
            jQuery(this).addClass('node');
        }
    });
    jQuery('.treenav').find('ul').hide();

    jQuery('.treenavbrand').find('li').each(function () {
        if (jQuery(this).children('ul').length > 0) {
            jQuery(this).addClass('node');
        }
    });

    jQuery('.node a:first-child').click(function () {
        jQuery(this).parent('li').toggleClass('collapsed').children("ul").toggle('blind', 500);
    });
    // Watermark
    jQuery('.watermark').each(function () {
        if (jQuery(this).val() == "") {
            jQuery(this).val(jQuery(this).attr('title')).addClass('watermarked');
        }
        jQuery(this).focus(function () {
            if (jQuery(this).val() == jQuery(this).attr('title')) {
                jQuery(this).val("").removeClass('watermarked');
            }
        });
        jQuery(this).blur(function () {
            if (jQuery(this).val() == "") {
                jQuery(this).val(jQuery(this).attr('title')).addClass('watermarked');
            }
        });

    });
    // expanded hot state
    var expandedLi = jQuery('.accordionNav').attr('id');
    jQuery('#S_' + expandedLi).addClass('hot').children('ul').show();
    // Carouselle Lite
    var imgCounter = 0;
    imgCounter = jQuery('#tmbCounter').val();

    if (imgCounter > 4) {
        jQuery(".jCarouselLite").jCarouselLite({
            btnNext: "#carousel-left",
            btnPrev: "#carousel-right",
            circular: true,
            visible: 4
        });
    }
    else {
        jQuery("#carousel-left").hide();
        jQuery("#carousel-right").hide();
    }
    //Spin Button
    var spinOptions = {
        min: 1,
        max: 100,
        step: 1
    }
    jQuery(".add-qty").SpinButton(spinOptions);

});         //end document.ready
jQuery(function () {
    // Quick view on mouse over
    jQuery('.prodimg').live('mouseover', function () {
        var quickpath = "/shipcalc.asp?prod=" + jQuery(this).attr('rel');
        var quickpos = jQuery(this).offset();
        var quickwidth = jQuery(document).width();
        var imgheight = jQuery(this).height();
        var imgwidth = jQuery(this).width();

        jQuery('.quickview').not(jQuery(this).children('.quickview')).hide();

        if (quickpos.left < (quickwidth / 2)) {
            jQuery(this).children('.quickview').load(quickpath).offset({ top: Math.round(quickpos.top - imgheight), left: Math.round(quickpos.left + imgwidth) }).show();
        }
        else {
            jQuery(this).children('.quickview').load(quickpath).offset({ top: Math.round(quickpos.top - imgheight), left: Math.round(quickpos.left - 390) }).show();
        }

    });
    jQuery('.prodimg').live('mouseleave', function () {
        jQuery('.quickview').hide().css({ 'top': '0', 'left': '0' }).empty();
    });
    jQuery('.quickview').live('mouseleave', function () {
        jQuery(this).hide().css({ 'top': '0', 'left': '0' }).empty();
    });
});

var aAccessories = new Array();

function toggleAcc(elementID, productID) {
    if (jQuery(elementID).checked) {
        aAccessories.splice(aAccessories.length, 0, productID);
    }
    else {
        var index = jQueryA(aAccessories).indexOf(productID);
        if (index >= 0) { aAccessories.splice(index, 1); }
    }
}

function addAccToOrder(prod) {
    var options = '';
    if (jQuery('#aAccessories')) {
        //found options
        options = jQuery('#aAccessories').val();
    }
    addToCartAndShow('#cartarea', prod, 1, options);
}



function SelectAll() {

    var inputs = document.getElementsByTagName("input")
    if (inputs.length) {
        for (i = 1; i < inputs.length; i++) {
            if (inputs[i].type == "checkbox") { inputs[i].checked = false; }
        }
    }
}

function replaceImageAndZoom(element, size, image) {
    element = "#" + element;
    var thumb = '/GetDynamicImage.aspx?path=' + image + '&h=' + size + '&w=' + size;
    jQuery(element).attr("src", thumb);
}
function getcartarea(divID) {
    onSubDiv = false;
    jQuery(divID).html("<img src=\"/images/loading.gif\" />");
    jQuery(divID).removeClass('Description');
    jQuery(divID).slideDown("slow");
    jQuery.get('/ajax_addedtocartpulldown.asp', function (data) {
        jQuery((divID)).html(data);

    });

}
function addToCartAndShow(divID, prod, qty, options) {
    jQuery(divID).html("<img src=\"/images/loading.gif\" /> Adding to Cart...");
    jQuery(divID).removeClass('Description');
    jQuery(divID).slideDown("slow");
    var url = '/ajax_addedtocartpulldown.asp?prod=' + prod + '&quantity=' + qty.toString() + '&options=' + options;

    jQuery.get(url, function (data) {
        jQuery((divID)).html(data);
        window.setTimeout("hidecartarea('" + divID + "')", 3000);
    });
}
function hidecartarea(divID, parentdivID) {
    window.setTimeout("hideIt('" + divID + "')", 500);
}
function hideIt(divID) {
    if (!onSubDiv)
        jQuery(divID).slideUp("slow");
}

//AJAX Narrow By Functions
var page = '1';
var sort = 'PA';
var psize = '36';
var pagetop = true;

function filtersubcat() {
    var subcat = jQuery("#subcatid").val();
    var catID = jQuery("#catid").val();
    var divID = "#Content";

    if (pagetop) {
        sort = jQuery('#sort option:selected').val();
        psize = jQuery('#psize option:selected').val();
    }
    else {
        sort = jQuery('#sort2 option:selected').val();
        psize = jQuery('#psize2 option:selected').val();
    }

    jQuery(divID).fadeOut("slow", function () {
        // Animation complete.
        var brand = "";
        var cat = "";
        var dept = "";

        jQuery('input:checkbox').each(function () {
            if (this.checked) {
                if (this.name.indexOf("cat_") > -1) {
                    cat = cat + "," + this.value;
                }
                if (this.name.indexOf("brand_") > -1) {
                    brand = brand + "," + this.value
                }

                if (this.name.indexOf("dept_") > -1) {
                    dept = dept + "," + this.value
                }
            }
        });
        if (cat != "") {
            cat = cat.substring(1)
        }

        if (brand != "") {
            brand = brand.substring(1)
        }

        if (dept != "") {
            dept = dept.substring(1)
        }
        var url = "/ajax_subcat.asp?page=" + page + "&deptlist=" + dept + "&lsGrouping=" + catID + "&catlist=" + cat + "&catSQL=" + cat + "&brandlist=" + brand + "&subcat=" + subcat + "&sort=" + sort + "&psize=" + psize

        jQuery.get(url, function (data) {
            //ie
            if (document.all) {
                document.getElementById("Content").innerHTML = data;
            }
            else {
                jQuery(divID).html(data);
            }

            jQuery(divID).fadeIn("slow");

        });
    });
}


function clearOptions(selectBox) {
    var retStr = "";
    for (i=selectBox;i<=selectBox+25;i++) {
	    if (jQuery("#ddlOption" + i)) {
		jQuery("#ddlOption" + i).find('option').remove().end();        
		jQuery("#ddlOption" + i).hide();
	    }
	    else {
	    	break;
	    }
    }
    
    //now for each one that is visible, build the string back to compare to build the next drop down for only those that apply.
    for (i=1;i<=selectBox;i++) {
    	    if (jQuery("#ddlOption" + i)) {
    		if (jQuery("#ddlOption" + i).is(':visible')) {
    			retStr += jQuery("#ddlOption" + i).val() + ";";
    		}
    	    }
    	    else {
    	    	break;
    	    }
    }
    if (retStr != "") {
    	retStr = retStr.slice(0,-1);
    }
    return retStr;
    
}

function getHiddenIDFromSelectLists() {
	var retStr = "";
	//now for each one that is visible, build the string back to compare to build the next drop down for only those that apply.
	    for (i=1;i<=100;i++) {
	    	    if (jQuery("#ddlOption" + i)) {
	    		if (jQuery("#ddlOption" + i).is(':visible')) {
	    			retStr += jQuery("#ddlOption" + i).val() + ";";
	    		}
	    	    }
	    	    else {
	    	    	break;
	    	    }
	    }
	    if (retStr != "") {
	    	retStr = retStr.slice(0,-1);
	    }
    
    	var aOptions = jQuery('#productOptionValues').find(':input[type=hidden]'); 
	            for (var i = 0, len = aOptions.length; i < len; ++i) {
	            	
	            	if (aOptions[i].value.split('|')[1] == retStr) {
	            		return aOptions[i].id;
	            	}
	            }		          
}



function addSelectOption(selectObj, text, value, isSelected) {
    if (selectObj != null && selectObj.options != null) {
        selectObj.options[selectObj.options.length] = new Option(text, value, false, isSelected);
    }
}

function swapProductOptions(ddlToShow) {
	
	var prevDDL = ddlToShow - 1;
	var lookupText = "";
	var endOfOptions = false;
	
	//jQuery("#ddlOption" + ddlToShow).slideDown('slow');
	jQuery("#addToCartBtn").hide();
		
	    
	    jQuery('#options').val('');
	    if (jQuery("#ddlOption" + ddlToShow) && jQuery('#productOptionValues')) {
	        lookupText = clearOptions(ddlToShow);	        
	        if (jQuery('#ddlOption' + (prevDDL)).value != '' || jQuery('#ddlOption' + prevDDL).value == '1') {
	        
	            var aValues = new Array();
	            var aOptions = jQuery('#productOptionValues').find(':input[type=hidden]'); 
	            for (var i = 0, len = aOptions.length; i < len; ++i) {
			var aOption = aOptions[i].value.split('|')[1].split(';');
			var sOption = aOptions[i].value.split('|')[1];
			var iQty = aOptions[i].value.split('|')[3];
					
	                if (iQty != '' && iQty > -100) {				
	                	//This item has inventory, so let's try it out	                	
				
				try {
					
					if(sOption.indexOf(lookupText) == 0) {						
						var sValue = aOption[prevDDL].split('=')[1];
						if (jQuery.inArray(sValue, aValues) == -1) {
							var SOptionType = aOption[prevDDL].split('=')[0];
							aValues.splice(aValues.length + 1, 0, sValue);
						}
					}
				}
				catch (e) {
					//we have reached the end!

				    if (aValues.length == 0) {
				        hiddenName = getHiddenIDFromSelectLists();
				        endOfOptions = true;
				        break;
				    }
				}
				
	                }
	            }
					
		    if (!endOfOptions) {
			    for (var i = 0, len = aValues.length; i < len; ++i) {
				if (i == 0) {
					var oDDL = document.getElementById("ddlOption" + ddlToShow);
					addSelectOption(document.getElementById("ddlOption" + ddlToShow), 'Choose a ' + SOptionType, '', true);

				}
				addSelectOption(document.getElementById("ddlOption" + ddlToShow), aValues[i], SOptionType + '=' + aValues[i], false);
			    }


			    if (aValues.length > 0) {
				jQuery("#ddlOption" + ddlToShow).slideDown(.8);
			    }
			    else {
				jQuery("#ddlOption" + ddlToShow).slideUp(.8);
			    }			    
	            }
	            else {
	            	//We have enough options to make this thing work, check if we can show the button and do the rest of the logic for it!
	            	var partNo;
			var stock;
			var QtyToCompare;
			
			
			///////
			try {
            			QtyToCompare = jQuery("#" + hiddenName).val().split('|')[3];
            		}
           catch (e) {
               jQuery("#optionStock").html(" ");
            			return;
            			//exiting out
            			
            		}
			partNo = hiddenName;
            			
			stock = jQuery("#" + hiddenName).val().split('|')[6];
			if (stock == "") {
				stock = jQuery('#hdnStockStatus').val();
			}

			//Set part #
			if (jQuery("#partno")) {
				jQuery("#partno").html(partNo);
			}
			
			if (jQuery(".OurPrice").children(".Number")) {
				if (jQuery("#hdnPrice")) {					
					var upcharge = jQuery("#" + hiddenName).val().split('|')[2];
					upcharge = formatCurrency(parseFloat(upcharge) + parseFloat(jQuery("#hdnPrice").val()));
					jQuery(".OurPrice").children(".PriceAmount").children(".Number").html(upcharge);
				}
			}

			//set status
			if (jQuery("#optionStock")) {
				jQuery("#optionStock").html(stock);
			}

			//set button
			if (parseInt(QtyToCompare) > 0) {
				jQuery("#addToCartBtn").show();
			}
			else {
				jQuery("#optionStock").html(stock);
				jQuery("#addToCartBtn").hide();
			}
	            }
	        }	        
    	}
	
	
}

function validateForm() {
	var qty;
	qty = jQuery("#quantity").val();
	var stock;
	var groupID;
	var QtyToCompare;


	///////
	if (jQuery("#" + hiddenName)) {
		//options
		QtyToCompare = jQuery("#" + hiddenName).val().split('|')[3];
		if (parseInt(QtyToCompare) < parseInt(qty)) {
					alert('Low Stock Alert.  Only ' + QtyToCompare + ' available for purchase.');
					return(false);
		}
		
		jQuery("#options").val(jQuery("#" + hiddenName).val().split('|')[0] + ';' + hiddenName);		
		return(true);
	}
	else {
		//no options
		QtyToCompare = jQuery("#hdnQty").val();
		if (parseInt(QtyToCompare) < parseInt(qty)) {
			alert('Low Stock Alert.  Only ' + QtyToCompare + ' available for purchase.');
			return(false);
		}
		return(true);
	}
}


function formatCurrency(strValue)
{
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);
 
	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-') + '$' + dblValue + '.' + strCents);
}

//slideshow
jQuery(function () {
    jQuery('#slideshow').cycle({
        delay: 8000,
        speed: 500,
        timeout: 8000
    });
});
//Slide cart functions
