jQuery.noConflict();

function filterClick(displayName, attributeName) {
    _gaq.push(['_trackEvent', 'Filters', displayName, attributeName]);
}

function trackTopNav(action, label) {
    googleTrackEvent("Top Nav", action, label);
}

function googleTrackEvent(category, action, label) {
    _gaq.push(['_trackEvent', category, action, label]);
}

function formatCurrency(amount) {
    var i = parseFloat(amount);
    if (isNaN(i)) { i = 0.00; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if (s.indexOf('.') < 0) { s += '.00'; }
    if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
}
function addProduct(prodID, dept, cat, option) {
    var myHREF = "/preorderform.asp?dept=" + dept + "&cat=" + cat + "&prod=" + prodID + "&options=" + option + "&qty=1&personalize=no";
    location.href = myHREF;
}
function selectColor(option, text) {
    $('hdnColor').value = option.replace('\'', '');
    $('lblColor').innerHTML = text.replace('\'', '');
}
function validateProduct() {
    if ($('hdnColor').value.length > 0) {
        return true;
    }
    else {
        alert('Please select a color from the color list.');
        return false;
    }
}

function replaceImage(htmlID, oldwidth, newwidth, container, num) {
    //remove the selected class from whatever thumbnail was selected
    $$('#' + container + ' .ThumbnailSelected').each(function(item) { item.removeClassName('ThumbnailSelected').addClassName('Thumbnail'); });

    //add the selected class to the thumbnail being selected
    $(container + '_link_' + num).removeClassName('Thumbnail').addClassName('ThumbnailSelected');

    //now replace the image
    var oldparams = "&w=" + oldwidth + "&h=" + oldwidth;
    var newparams = "&w=" + newwidth + "&h=" + newwidth;

    $(htmlID).src = $(container + '_img_' + num).src.replace(oldparams, newparams);
}

function changeSwatch(colorID, switchDropdown) {
    //remove the selected class from whatever swatch was selected
    $$('#ColorSwatches .Selected').each(function(item) { item.removeClassName('Selected').addClassName('Unselected'); });

    //add the selected class to the swatch being selected
    $('swatch_' + colorID).removeClassName('Unselected').addClassName('Selected');

    //change the dropdown box value
    //  should be false if event was triggered by dropdown
    if (switchDropdown) {
        for (var i = 0; i < $('selectableOptions').length; i++) {
            if ($('selectableOptions')[i].value == colorID) {
                $('selectableOptions').selectedIndex = i;
                break;
            }
        }
    }

    //hide all the thumbnail sections
    $$('#productThumbnails div').each(function(item) { item.hide(); });

    //show the thumbnails for this option
    $('thumbs_' + colorID).show();

    //replace the main image with the first thumbnail
    replaceImage('imgMain', 70, 385, 'thumbs_' + colorID, 0);

    $('options').value = $('option_' + colorID).value;
    
    changePrice(colorID);
    changeSKU(colorID);
    changeStockStatus(colorID);
}

function changePrice(colorID) {
    if ($('values_' + colorID)) {
    	var offset = $('values_' + colorID).value.split(';')[0];
    	if (parseFloat(offset) >= 0) {
    		if (parseFloat($('baseSale').value) == 0) {
    			$('Price1').innerHTML = '';
    			$('Price2').innerHTML = '$' + formatCurrency(parseFloat($('basePrice').value) + parseFloat(offset));
    		}
    		else {
    			$('Price1').innerHTML = '$' + formatCurrency(parseFloat($('basePrice').value) + parseFloat(offset));
    			$('Price2').innerHTML = '$' + formatCurrency(parseFloat($('baseSale').value) + parseFloat(offset));
    		}
    	} 
    	else {
    		if (parseFloat($('baseSale').value) == 0) {
    			$('Price1').innerHTML = '$' + formatCurrency(parseFloat($('basePrice').value));
    			$('Price2').innerHTML = '$' + formatCurrency(parseFloat($('basePrice').value) + parseFloat(offset));
    		}
    		else {
    			$('Price1').innerHTML = '$' + formatCurrency(parseFloat($('basePrice').value)) + ' $' + formatCurrency(parseFloat($('baseSale').value));
    			$('Price2').innerHTML = '$' + formatCurrency(parseFloat($('baseSale').value) + parseFloat(offset));
    		}
    	}
    }
}

function changeSKU(colorID) {
    if ($('values_' + colorID)) {
        if ($('Sku')) {
            $('Sku').innerHTML = $('values_' + colorID).value.split(';')[1];
        }
    }
}

function changeStockStatus(colorID) {
    if ($('values_' + colorID)) {
        if ($('StockStatus')) {
        		var iThreshold = 0
            //  NR:  Waiting for stock status in product options
            var quantity = $('values_' + colorID).value.split(';')[2];
            var stockStatus = 1;

            if (quantity <= iThreshold)
                stockStatus = 2;
            if (stockStatus == 1) {
                $('StockStatus').removeClassName('OutOfStock');
                $('AddToCartButton').show();
                /*$('notifyMe').hide();*/
                $('Qty').disabled = false;
                var quantity = $('values_' + colorID).value.split(';')[2];
                var stockStatus = $('values_' + colorID).value.split(';')[3];
            }
            else {
                $('StockStatus').addClassName('OutOfStock');
                $('AddToCartButton').hide();
                $('Qty').disabled = true;
                stockStatus = 2;
                /*var notifyMe = document.getElementById('notifyMeLink').href;
                document.getElementById('notifyMeLink').href = notifyMe + '&opt=' + colorID;
                $('notifyMe').show();*/
            }

            if ($('stockStatusMessage_' + stockStatus))
                $('StockStatus').innerHTML = $('stockStatusMessage_' + stockStatus).value;
            else
                $('StockStatus').innerHTML = $('stockStatusMessage_1').value;
        }
    }
}

function verifyQty() {
	if ($('selectableOptions')) {
		var colorID = $('selectableOptions').value;
		var quantity = $('values_' + colorID).value.split(';')[2];
		if (parseInt($('Qty').value) > parseInt(quantity)) {
			alert('Low stock alert, only ' + quantity + ' available for purchase.');
			return false;
		}
	}	
	else {
		if (parseInt($('Qty').value) > parseInt($('baseQty').value)) {
			alert('Low stock alert, only ' + $('baseQty').value + ' available for purchase.');
			return false;
		}
	}
	return true;
}
/* *** BEGIN JQUERY JS *** */
jQuery(document).ready(function ($) {
    $('.filterNav h3').live('click', function (e) {
        e.preventDefault();
        $(this).toggleClass('open');
        $(this).siblings('.filterGroup').toggleClass('open');
    });
    $('.filterNav .field label').live('click', function () {
        $(this).parent().children('input').attr('checked', true);
        ajaxAttributeFilters();
    });
    if (window.location.hash.length > 0 || typeof (lsCurrentCatId) != 'undefined') {
        hashDance();
    } else {
        jQuery('.pageLoadEl').hide();
        jQuery('div.filterNavWrap2012, div.refineSort, div#SubcatBox.productList').fadeIn();
    }
    jQuery(window).hashchange(function () {
        hashDance()
    })
    accList = "";
    $('.prodAcc input').live('change', function () {
        jQuery('.prodAcc input:checked').each(function () {
            if (accList == "") {
                accList = jQuery(this).attr('value')
            } else {
                accList = accList + ',' + jQuery(this).attr('value')
            }
        })
        jQuery('#accList').val(accList);
        accList = "";
    });
    $('.more').live('click', function () {
        if ($(this).text() == "more >") {
            $(this).text('show fewer >');
        } else {
            $(this).text('more >');
        }
        $(this).nextAll('.field').toggleClass('collapsed')
    })

    $('div.megamenu a').live('click', function () {
        trackTopNav('MM-Click', jQuery(this).attr('title') + "-Click");
    });
});

function changeBrandDevice(select) {
    (function ($) {
        select = $('#'+select);
        var displayName = select.attr('name');
        var attributeName = select.find("option:selected").text();
        if (select.attr("id") == "Brand_select")
            $('#Devices_select').val("");
        filterClick(displayName, attributeName);
        ajaxAttributeFilters();
    })(jQuery)
}

/* BBQ Filters */
function hashDance() {
    hashString = window.location.hash.substr(1);
    if (hashString.indexOf("subcat") < 1 && jQuery('#subcatid').length) {
        hashString = hashString + "&subcat=" + jQuery('#subcatid').attr('value')
    }
    if (window.location.hash.length < 1 && jQuery('#subcatid').length) {
        hashString = "subcat=" + jQuery('#subcatid').attr('value')
    }
    if (typeof(lsCurrentCatId) != 'undefined') {
        if (hashString.indexOf("class=") >= 0) {
            hashString = hashString.replace(new RegExp("class=([0-9,]+)"), "class=$1" + lsCurrentCatId + ",")
        }
        else {
            if (hashString.length > 0)
                hashString = hashString + "&"
            hashString = hashString + "class=," + lsCurrentCatId + ","
        }
    }
    if (typeof(lsCurrentCatColorName) != 'undefined') {
        if (hashString.indexOf("color=") >= 0) {
            hashString = hashString.replace(new RegExp("color=([a-zA-Z]+)?"), "color=" + lsCurrentCatColorName)
        }
        else {
            if (hashString.length > 0)
                hashString = hashString + "&"
            hashString = hashString + "color=" + lsCurrentCatColorName
        }
    }
    ajaxPanel(hashString);
    //verifyAttributeChecks();
}
function ajaxHash(filters) {
    jQuery.bbq.pushState(filters);
}
function ajaxSort(s) {
   ajaxHash("sort="+s);
}
filteredList = ""
function ajaxAttributeFilters() {
    attributeList = ""
    brandList = ""
    colorList = ""
    colorAttr =""
    filteredList = ""

    if (typeof (lsCurrentCatId) != 'undefined' && typeof (lsCurrentCatColorName) == 'undefined') {
        attributeList = "," + lsCurrentCatId;
        filteredList = lsCurrentCatParentId  + "|" + lsCurrentCatId;
    }
    jQuery('.attributeFilter:checked').each(function () {
        if (attributeList == "") {
            attributeList = ',' + jQuery(this).attr('value');
            filteredList = jQuery(this).attr('rel');
        }
        else {
            attributeList = attributeList + ',' + jQuery(this).attr('value');
            filteredList = filteredList + ',' + jQuery(this).attr('rel');
        }
    });
    jQuery('.classificationSelect').each(function () {
        selectCatId = jQuery(this).val();
        if (selectCatId.length > 0) {
            selectParentId = jQuery(this).attr('rel');
            if (attributeList == "") {
                attributeList = ',' + selectCatId;
                filteredList = selectParentId + "|" + selectCatId;
            }
            else {
                attributeList = attributeList + ',' + selectCatId;
                filteredList = filteredList + ',' + selectParentId + "|" + selectCatId;
            }
        }
    });
    if (typeof (lsCurrentCatColorName) != 'undefined') {
        colorList = lsCurrentCatColorName;
        colorAttr = ',' + lsCurrentCatId;
    } else {
        jQuery('.colorFilter:checked').each(function () {
            colorList = jQuery(this).attr('title');
            colorAttr = ',' + jQuery(this).attr('value');
        });
    }
    if (attributeList == "") {
        attributeList = colorAttr+',';
    } 
    else {
        attributeList = attributeList + colorAttr+',';
    }
    jQuery('.brandFilter:checked').each(function () {
        if (brandList == "") {
            brandList = jQuery(this).attr('value')
        } else {
            brandList = brandList + ',' + jQuery(this).attr('value')
        }
    })
    ajaxHash('page=1&class=' + attributeList + '&brandList=' + brandList + '&color=' + colorList)
}
function ajaxPanel(urlVariables) {
   var target = '.subsubPage'
   panelHeight = jQuery(target).height()
   var loadingTemplate = '<div class="subcatBorderTop"></div><div class="loadingElement" style="height:' + panelHeight + 'px;"><img src="/images/loading.gif"></div><div class="subcatBorderBottom"></div>'
   jQuery('html, body').animate({ scrollTop: 0 }, 0);
   jQuery(target).html(loadingTemplate);
   subCatId = jQuery('#subcatid').attr('value')
   
   //BUILD THE URL STRING
   var url = '/Templates/ajax_subcat.asp?' + urlVariables
   jQuery.get(url, function (data) {
       jQuery(target).html(data);
   }).success(function () {
       var checkSelCol = 0;
       var checkSelAttr = 0;
       var allColorList = "";
       var allAttrList = "";
       jQuery('.pageLoadEl').remove();
       jQuery('div.filterNavWrap2012, div.refineSort, div#SubcatBox.productList').fadeIn();
       jQuery('div.field label.selectedColor').each(function () {
           var attribute_id = jQuery(this).attr('id').substr(2);
           var classification_id = jQuery('#cat_' + attribute_id).attr('rel').split('|')[0];
           if (jQuery('#cat_' + attribute_id).hasClass('colorFilter')) {
               jQuery(this).parent('.field').siblings('.field').hide();
           }
           jQuery(this).parent('.field').removeClass('collapsed');
           var attrName = jQuery(this).parent().children('input').attr('title');
           var parent_name = jQuery('#sel_subcat_' + classification_id).parent('div.filter.open').children('h3').html();
           if (allColorList == "") {
               allColorList = attribute_id;
           } else {
               allColorList = allColorList + ',' + attribute_id;
           }

           jQuery('#sel_subcat_' + classification_id).css('display', 'block');
           if (typeof (lsCurrentCatId) != 'undefined' && lsCurrentCatId == attribute_id) {
           } else {
               jQuery('.attrClearWrap').css('display', 'block');
               checkSelCol = parseInt(checkSelCol) + 1;
               jQuery('.attrClearContent').append('<h1>' + parent_name + '</h1><div class="remove_attribute" onclick="remove_attribute(\'' + attribute_id + '\');"><span class="ra_x"></span> ' + attrName + '</div>');
               jQuery('#sel_subcat_' + classification_id).append('<div class="remove_attribute" onclick="remove_attribute(\'' + attribute_id + '\');">Clear ' + parent_name + '</div>');
           }
       });
       jQuery('div.field label.selectedAttr').each(function () {
           var attribute_id = jQuery(this).attr('id').substr(2);
           var classification_id = jQuery('#cat_' + attribute_id).attr('rel').split('|')[0];
           if (jQuery('#cat_' + attribute_id).hasClass('attributeFilter')) {
               jQuery(this).parent('.field').siblings('.field').hide();
           }
           jQuery(this).parent('.field').removeClass('collapsed');
           var attrName = jQuery(this).parent().children('input').attr('title');
           var parent_name = jQuery('#sel_subcat_' + classification_id).parent('div.filter.open').children('h3').html();
           if (allAttrList == "") {
               allAttrList = attribute_id;
           } else {
               allAttrList = allAttrList + ',' + attribute_id;
           }

           jQuery('#sel_subcat_' + classification_id).css('display', 'block');
           if (typeof (lsCurrentCatId) != 'undefined' && lsCurrentCatId == attribute_id) {
           } else {
               jQuery('.attrClearWrap').css('display', 'block');
               checkSelAttr = parseInt(checkSelAttr) + 1;
               jQuery('.attrClearContent').append('<h1>' + parent_name + '</h1><div class="remove_attribute" onclick="remove_attribute(\'' + attribute_id + '\');"><span class="ra_x"></span> ' + attrName + '</div>');
               jQuery('#sel_subcat_' + classification_id).append('<div class="remove_attribute" onclick="remove_attribute(\'' + attribute_id + '\');">Clear ' + parent_name + '</div>');
           }
       });
       if ((parseInt(checkSelAttr) + parseInt(checkSelCol)) > 1) {
           //allAttrList allColorList
           removeAllList = allAttrList + ',' + allColorList
           jQuery('.attrClearContent').append('<div class="remove_attribute_all" onclick="remove_all_attributes();">Remove All</div>');
       };
   });
}
function remove_attribute(attr_id) {
    jQuery('input#cat_'+ attr_id).attr('checked', false);
    ajaxAttributeFilters();
}
function remove_all_attributes(attr_id_list) {
    jQuery('.filterNav input').each(function () {
        jQuery(this).attr('checked', false);
    });
    ajaxAttributeFilters();
}
function CheckEmailCustom(camefromurl) {
    email = document.getElementById("txtemail");
    if (email == null) {
        email = document.getElementById("NewsletterInput");
    }

    var EnteredEmail = email.value;
    var url = camefromurl + "Emailfunction.asp?Email=" + EnteredEmail;

    var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i

    if (filter.test(EnteredEmail)) {
        loadEmail(url);
        var txtEmail = '/emailSignupThanks.asp?txtEmail=' + EnteredEmail;
        jQuery.get(txtEmail, function (data) {
            //alert(data);
        })
        return false;
    }
    else {
        document.getElementById('emailresults').innerHTML = "Please Enter a valid email address"
    }
}

