/* Common Javascript functions for use throughout Interspire Shopping Cart */
Array.prototype.unique = function(){
	this.sort();
	for ( var i = 1; i < this.length; i++ ) {
		if ( this[i] === this[i-1] ) {
			this.splice(i--, 1);
		}
	}
};

String.prototype.format = function(){
    var args = arguments;
    return this.replace(/\{(\d+)\}/g,               
        function(m,i){
            return args[i];
        });
}

function setSearchBtn(){
	var hasNew = true;
	if(hasNew)
		activeSearch();
	else
		inactiveSearch();
}

function activeSearch(){
	$('.searchBtn_inactive').removeClass('searchBtn_inactive').addClass('searchBtn');
	$('.searchBtn').attr('disabled', false);
	$('#search_arrow').show();
}

function inactiveSearch(){
	$('.searchBtn').removeClass('searchBtn').addClass('searchBtn_inactive');
	$('.searchBtn').attr('disabled', true);
	$('#search_arrow').hide();
}

function gotoPage(obj, gotoLink, pageEnd){
        pageEnd = (Number)(pageEnd);
        var pageNo = $(obj).prev().val();
        if(pageNo.match(/\d+/) && pageNo>0 && pageNo<=pageEnd){
            //obj.href = gotoLink.replace(/(\/page\/)\d+/g, '$1'+pageNo);
	    $('#current_page').attr('value', pageNo);
	    $('#searchFrm').submit();
        }
        else
            alert('Please input a correct page number!');
}

function OrderSort(orderby, sortby){
	$('#current_orderby').attr('value', orderby);
	$('#current_sortby').attr('value', sortby);
	$('#searchFrm').submit();
}

function checkQuickSearch(){
	var searchVal = $('#search_partnum').val();
	if($.trim(searchVal).length == 0){
		alert('Input some part numbers here please!')
		$('#search_partnum').focus();
	}else{
		searchVal = MakeURLSafe(htmlspecialchars($.trim(searchVal)));
		//location.href =  '/action/quicksearch/search_partnum/' + searchVal;
		$('#quickSearchFrm').submit();
	}
}

function SetSelectionByCookie(Toggle, cookiePath, cookieDomain){
	var Brands = [], Series = [], Categories = [], Subcategories = [], Years=[], Makes=[], Models=[];
	var cookieBrand = getCwCookie('last_search_selection[brand]');
	var cookieSeries = getCwCookie('last_search_selection[series]');
	var cookieCategory = getCwCookie('last_search_selection[category]');
	var cookieSubcategory = getCwCookie('last_search_selection[subcategory]');
	var cookieYear = getCwCookie('last_search_selection[year]');
	var cookieMake = getCwCookie('last_search_selection[make]');
	var cookieModel = getCwCookie('last_search_selection[model]');
	
	if($.trim(cookieBrand).length>0)
	    Brands = cookieBrand.split('_');
	if($.trim(cookieSeries).length>0)
	    Series = cookieSeries.split('_');
	if($.trim(cookieCategory).length>0)
	    Categories = cookieCategory.split('_');
	if($.trim(cookieSubcategory).length>0)
	    Subcategories = cookieSubcategory.split('_');
	if($.trim(cookieYear).length>0)
	    Years = cookieYear.split('_');
	if($.trim(cookieMake).length>0)
	    Makes = cookieMake.split('_');
	if($.trim(cookieModel).length>0)
	    Models = cookieModel.split('_');
	
	var last_search_selection = {
	    'brand': Brands,
	    'series': Series,
	    'category': Categories,
	    'subcategory': Subcategories,
	    'year': Years,
	    'make': Makes,
	    'model': Models
	}
	
	$('li.leftmenuitem > input[type=checkbox]','#SideCategoryList').each(function(){
	    if($.inArray(this.value, last_search_selection.category) != -1){
		this.checked = 'checked';
		if(Toggle && Toggle.category)
			toggleCategory($(this).prev(), cookiePath, cookieDomain);
	    }else{
		this.checked = '';
	    }
	});
	
	$('.subcategoryList input[type=checkbox]','#SideCategoryList').each(function(){
            if($.inArray(this.value, last_search_selection.subcategory) != -1){
		this.checked = 'checked';
	    }else{
		this.checked = '';
	    }
	});
	
	$('li.leftmenuitem > input[type=checkbox]','#SideBrandList').each(function(){
	    if($.inArray(this.value, last_search_selection.brand) != -1){
		this.checked = 'checked';
		if(Toggle && Toggle.brand)
			toggleBrand($(this).prev(), cookiePath, cookieDomain);
	    }else{
		this.checked = '';
	    }
	});
	
	$('.seriesList input[type=checkbox]','#SideBrandList').each(function(){
            if($.inArray(this.value, last_search_selection.series) != -1){
		this.checked = 'checked';
	    }else{
		this.checked = '';
	    }
	});
	
	$('input[type=checkbox]','#SideYearList').each(function(){
	    if($.inArray(this.value, last_search_selection.year) != -1){
		this.checked = 'checked';
	    }else{
		this.checked = '';
	    }
	});
	
	$('li.leftmenuitem > input[type=checkbox]','#SideMakeList').each(function(){
	    if($.inArray(this.value, last_search_selection.make) != -1){
		this.checked = 'checked';
		if(Toggle && Toggle.make)
			toggleMake($(this).prev(), cookiePath, cookieDomain);
	    }else{
		this.checked = '';
	    }
	});
	
	$('.modelList input[type=checkbox]','#SideMakeList').each(function(){
            if($.inArray(this.value, last_search_selection.model) != -1){
		this.checked = 'checked';
	    }else{
		this.checked = '';
	    }
	});
	
	var _Years = new Object();
	var _Makes = new Object();
	var _Models = new Object();
	$.each(last_search_selection.year, function(){
		if(_Years[this] == undefined)
		  _Years[this] = new Array();
	});
	
	var makeArr = [];
	$.each(last_search_selection.make, function(){
	    makeArr.push(MakeURLSafe(this));
	    if(_Makes[this] == undefined)
		  _Makes[this] = new Array();
	});
	
	var modelArr = [];
	$.each(last_search_selection.model, function(){
	    modelArr.push(MakeURLSafe(this));
	    if(_Models[this] == undefined)
		  _Models[this] = new Array();
	});
	
	$('#side_selected_year').html(GenerateSelectionStr(_Years));
	$('#side_selected_make').html(GenerateSelectionStr(_Makes));
	$('#side_selected_model').html(GenerateSelectionStr(_Models));
	
	$.ajax({
		url: '/remote.php?w=groupselection',
		type: 'GET', 
		cache: false,
		dataType: 'json',
		data: { 
		    'brand': last_search_selection.brand,
		    'series': last_search_selection.series,
		    'category': last_search_selection.category,
		    'subcategory': last_search_selection.subcategory,
		    'year': last_search_selection.year,
		    'make': makeArr,
		    'model': modelArr
		},
		error: function(){
		//  alert('Error loading XML document');
		},
		success: function(data)
		{
		    if(data != null){
			//$('#side_selected_year').html(GenerateSelectionStr(_Years));
			$('#side_selected_brand').html(GenerateSelectionStr(data.brands));
			$('#side_selected_category').html(GenerateSelectionStr(data.categories));
			//$('#side_selected_make').html(GenerateSelectionStr(data.makes));
		    }
		    
		    ShowNewsiteInstruction();
		}
	});

}

function filterMake(cookiePath, cookieDomain){
	var cookieYear = getCwCookie('last_search_selection[year]');
        var cookieMake = getCwCookie('last_search_selection[make]');
        var cookieModel = getCwCookie('last_search_selection[model]');
	
	$.ajax({
            url: '/remote.php?w=filterMakeByYear',
            type: 'GET', 
            cache: false,
            dataType: 'text',
            data: {'year': cookieYear, 'make': cookieMake, 'model': cookieModel},
            error: function(){
            },
            success: function(data)
            {
                $('#SideMakeList').replaceWith(data);
		SetSelectionByCookie({make: true}, cookiePath, cookieDomain);
                //updateMakeSelection(cookiePath, cookieDomain);
            }
        });
}
    
function filterCategory(cookiePath, cookieDomain){
        var cookieCategory = getCwCookie('last_search_selection[category]');
	var cookieSubcategory = getCwCookie('last_search_selection[subcategory]');
        var cookieBrand = getCwCookie('last_search_selection[brand]');
        var cookieSeries = getCwCookie('last_search_selection[series]');
        var cookieYear = getCwCookie('last_search_selection[year]');
        var cookieMake = getCwCookie('last_search_selection[make]');
        var cookieModel = getCwCookie('last_search_selection[model]');
        
        $.ajax({
            url: '/remote.php?w=filterCategoryByBrand',
            type: 'POST', 
            cache: false,
            dataType: 'text',
            data: {'brand': cookieBrand,
	           'sereis': cookieSeries,
	           'category': cookieCategory,
		   'subcategory': cookieSubcategory,
		   'year': cookieYear,
		   'make': cookieMake,
		   'model': cookieModel},
            error: function(){
            },
            success: function(data)
            {
                $('#SideCategoryList').replaceWith(data);
		SetSelectionByCookie({category: true}, cookiePath, cookieDomain);
                //updateCatSelection(cookiePath, cookieDomain);
            }
        });
}

function updateBrandSelection(cookiePath, cookieDomain, forceFilter){
	var checkBrand = [];
	var selectBrand = [];
	var selectSeries = [];
	var _Brands = new Object();
	
	$('li.leftmenuitem > input[type=checkbox]:checked','#SideBrandList').each(function(){
		var _brandName = $(this).next().html();
		if(_Brands[_brandName] == undefined)
		  _Brands[_brandName] = new Array();
		  
		selectBrand.push($(this).val());
	});

	$('.seriesList input[type=checkbox]:checked', '#SideBrandList').each(function(){
		var seriesName = $(this).next().html();
		var brandNode = $(this).parent().parent();
		var brandCheckbox = brandNode.parent().parent().find('input[type=checkbox]:first');
		var brandName = brandCheckbox.next().html();
		if(seriesName != '')
		  _Brands[brandName].push(seriesName);
	  
		selectSeries.push(this.value);
	});

	$('input[type=checkbox]:checked', '#BsList').each(function(){
	    var tmp = $.trim($(this).next().attr('name'));
	    tmp = tmp.replace(/\n/g, '');
	    if(_Brands[tmp] == undefined)
	      _Brands[tmp] = new Array();
		  
	    selectBrand.push($(this).val());
	});

	selectBrand.unique();
	$.each(_Brands, function(){this.unique();});
	$('#side_selected_brand').html(GenerateSelectionStr(_Brands));
	
	setCwCookie('last_search_selection[brand]', selectBrand.join('_'), 7, cookiePath, cookieDomain);
	setCwCookie('last_search_selection[series]', selectSeries.join('_'), 7, cookiePath, cookieDomain);
	
	if(getCwCookie('NI_Filter_Preference')=='' && selectBrand.length > 0){
		setCwCookie('NI_Filter_Preference', 'brand', 7, cookiePath, cookieDomain);
	}
	
	if(getCwCookie('NI_Filter_Preference')=='brand' || forceFilter){
		filterCategory(cookiePath, cookieDomain);
	}
	
	if(getCwCookie('last_search_selection[category]') == '' && getCwCookie('last_search_selection[brand]') == ''){
		deleteCwCookie('NI_Filter_Preference', cookiePath, cookieDomain);
	}
	
	setSearchBtn();
	ShowNewsiteInstruction();
}
    
function filterBrand(cookiePath, cookieDomain){
	var cookieBrand = getCwCookie('last_search_selection[brand]');
	var cookieSeries = getCwCookie('last_search_selection[series]');
	var cookieCategory = getCwCookie('last_search_selection[category]');
	var cookieSubcategory = getCwCookie('last_search_selection[subcategory]');
	var cookieYear = getCwCookie('last_search_selection[year]');
	var cookieMake = getCwCookie('last_search_selection[make]');
	var cookieModel = getCwCookie('last_search_selection[model]');
	
	$.ajax({
	    url: '/remote.php?w=filterBrandByCategory',
	    type: 'POST', 
	    cache: false,
	    dataType: 'text',
	    data: {'category': cookieCategory,
	           'subcategory': cookieSubcategory,
	           'brand': cookieBrand,
		   'series': cookieSeries,
		   'year': cookieYear,
		   'make': cookieMake,
		   'model': cookieModel},
	    error: function(){
	    },
	    success: function(data)
	    {
		$('#SideBrandList').replaceWith(data);
		SetSelectionByCookie({brand: true}, cookiePath, cookieDomain);
		//updateBrandSelection(cookiePath, cookieDomain);
	    }
	});
}

function updateCatSelection(cookiePath, cookieDomain, forceFilter){
	var checkCategory = [];
	var selectCategory = [];
	var selectSubcat = [];
	var _Cats = new Object();
	
	$('li.leftmenuitem > input[type=checkbox]:checked','#SideCategoryList').each(function(){
		var _catName = $(this).next().html();
		if(_Cats[_catName] == undefined)
		  _Cats[_catName] = new Array();
		  
		selectCategory.push($(this).val());
	});
	
	$('.subcategoryList input[type=checkbox]:checked', '#SideCategoryList').each(function(){
		var subcatName = $(this).next().html();
		var catNode = $(this).parent().parent();
		var catCheckbox = catNode.parent().parent().find('input[type=checkbox]:first');
		var catName = catCheckbox.next().html();
		if(subcatName != '')
		  _Cats[catName].push(subcatName);
		  
		selectSubcat.push(this.value);
	});
	
	$('input[type=checkbox]:checked', '#CategoryList').each(function(){
	    var tmp = $.trim($(this).parent().next().html());
	    tmp = tmp.replace(/\n/g, '');
	    if(_Cats[tmp] == undefined)
	      _Cats[tmp] = new Array();
	      
	    selectCategory.push($(this).val());
	});
	
	selectCategory.unique();
	$.each(_Cats, function(){this.unique();});
	$('#side_selected_category').html(GenerateSelectionStr(_Cats));
	
	setCwCookie('last_search_selection[category]', selectCategory.join('_'), 7, cookiePath, cookieDomain);
	setCwCookie('last_search_selection[subcategory]', selectSubcat.join('_'), 7, cookiePath, cookieDomain);
	    
	if(getCwCookie('NI_Filter_Preference')=='' && selectCategory.length > 0){
		setCwCookie('NI_Filter_Preference', 'category', 7, cookiePath, cookieDomain);
	}
	
	if(getCwCookie('NI_Filter_Preference')=='category' || forceFilter){
		filterBrand(cookiePath, cookieDomain);
	}
	
	if(getCwCookie('last_search_selection[category]') == '' && getCwCookie('last_search_selection[brand]') == ''){
		deleteCwCookie('NI_Filter_Preference', cookiePath, cookieDomain);
	}
	
	setSearchBtn();
	ShowNewsiteInstruction();
}

function updateMakeSelection(cookiePath, cookieDomain){
	var checkMake = [];
	var selectMake = [];
	var selectModel = [];
	var _Makes = new Object();
	var _NewMakes = new Object();
	var _Models = new Object();
	
	$('li.leftmenuitem > input[type=checkbox]:checked','#SideMakeList').each(function(){
		var _makeName = $(this).val();
		if(_Makes[_makeName] == undefined)
		  _Makes[_makeName] = new Array();
		  
		if(_NewMakes[_makeName] == undefined)
		  _NewMakes[_makeName] = new Array();
		  
		selectMake.push($(this).val());
	});
	
	$('.modelList input[type=checkbox]:checked', '#SideMakeList').each(function(){
		var modelName = $(this).val();
		var makeNode = $(this).parent().parent();
		var makeCheckbox = makeNode.parent().parent().find('input[type=checkbox]:first');
		var makeName = makeCheckbox.val();
		if(modelName != '')
		  _Makes[makeName].push(modelName);
		  
		if(_Models[modelName] == undefined)
		  _Models[modelName] = new Array();
		  
		selectModel.push(modelName);
	});
	
	/*
	$('input[type=checkbox]:checked', '#YmmList').each(function(){
	    var tmp = $.trim($(this).parent().next().html());
	    tmp = tmp.replace(/\n/g, '');
	    if(_Cats[tmp] == undefined)
	      _Cats[tmp] = new Array();
	      
	    selectCategory.push($(this).val());
	});*/
	
	selectMake.unique();
	selectModel.unique();
	$.each(_Makes, function(){this.unique();});
	$('#side_selected_make').html(GenerateSelectionStr(_NewMakes));
	$('#side_selected_model').html(GenerateSelectionStr(_Models));

	setCwCookie('last_search_selection[make]', selectMake.join('_'), 7, cookiePath, cookieDomain);
	setCwCookie('last_search_selection[model]', selectModel.join('_'), 7, cookiePath, cookieDomain);
	
	setSearchBtn();
	ShowNewsiteInstruction();
}

function updateYearSelection(cookiePath, cookieDomain){
	var selectYear = [];
	var _Years = new Object();
	
	$('input[type=checkbox]:checked','#SideYearList').each(function(){
		selectYear.push($(this).val());
		if(_Years[$(this).val()] == undefined)
		  _Years[$(this).val()] = new Array();
	});
	
	$('#side_selected_year').html(GenerateSelectionStr(_Years));
	setCwCookie('last_search_selection[year]', selectYear.join('_'), 7, cookiePath, cookieDomain);
	
	filterMake(cookiePath, cookieDomain);
	
	setSearchBtn();
	ShowNewsiteInstruction();
}

function FilterBrandCat(cookiePath, cookieDomain){
	if(getCwCookie('NI_Filter_Preference')=='brand'){
	    filterCategory(cookiePath, cookieDomain);
	}else if(getCwCookie('NI_Filter_Preference')=='category'){
	    filterBrand(cookiePath, cookieDomain);
	}
}

function updateVqPqSelection(cookiePath, cookieDomain){
	var selectVQ = [];
	var selectPQ = [];
	var _VQs = new Object();
	var _PQs = new Object();
	
	$('input[type=checkbox]:checked','#SideVqPqList').each(function(){
		var checkName = this.name;
		var reqName = checkName.replace(/^(vq|pq)\[([\s|\S]+)\](\[\])$/g,'$2');
		var checkVal = $(this).next().html();
		var className = $(this).parent().parent().parent().parent().parent().prev().find(':first-child').html();
		if(checkName.indexOf('vq[') == 0){
			selectVQ.push(reqName+"||"+checkVal);
			if(_VQs[className] == undefined)
				_VQs[className] = new Array();
			_VQs[className].push(checkVal);
		}else if(checkName.indexOf('pq[') == 0){
			selectPQ.push(reqName+"||"+checkVal);
			if(_PQs[className] == undefined)
				_PQs[className] = new Array();
			_PQs[className].push(checkVal);
		}
	});
	
	if(selectVQ.length > 0){
		$('#side_selected_vq').parent().parent().show();
		$('#side_selected_vq').html(GenerateSelectionStr(_VQs));
	}else{
		$('#side_selected_vq').parent().parent().hide();
	}
	
	if(selectPQ.length > 0){
		$('#side_selected_pq').parent().parent().show();
		$('#side_selected_pq').html(GenerateSelectionStr(_PQs));
	}else{
		$('#side_selected_pq').parent().parent().hide();
	}
	
	setCwCookie('last_search_selection[vq]', selectVQ.join('_'), 7, cookiePath, cookieDomain);
	setCwCookie('last_search_selection[pq]', selectPQ.join('_'), 7, cookiePath, cookieDomain);
	
	setSearchBtn();
}

function showVqPq(cookiePath, cookieDomain){
	
	var cookieCategory = getCwCookie('last_search_selection[category]');
	var cookieSubcategory = getCwCookie('last_search_selection[subcategory]');
        var cookieBrand = getCwCookie('last_search_selection[brand]');
        var cookieSeries = getCwCookie('last_search_selection[series]');
        var cookieYear = getCwCookie('last_search_selection[year]');
        var cookieMake = getCwCookie('last_search_selection[make]');
        var cookieModel = getCwCookie('last_search_selection[model]');
        
	if((cookieYear.length>0 && cookieMake.length>0 && cookieModel.length>0) ||
	   (cookieBrand.length>0 || cookieCategory.length>0)){
		$.ajax({
		    url: '/remote.php?w=showVqPq',
		    type: 'POST', 
		    cache: false,
		    dataType: 'json',
		    data: {'brand': cookieBrand,
			   'sereis': cookieSeries,
			   'category': cookieCategory,
			   'subcategory': cookieSubcategory,
			   'year': cookieYear,
			   'make': cookieMake,
			   'model': cookieModel},
		    error: function(){
		    },
		    success: function(data)
		    {
			var undefined;
			if(data != null){
				if(data.content != undefined){
					$('#SideVqPqList').replaceWith(data.content);
				}
				
				if(data.criteria != undefined){
					$('#multi_ymm_content > ul:gt(4)').remove();
					$('#multi_ymm_content').append(data.criteria);
				}
			}
			updateVqPqSelection(cookiePath, cookieDomain);
		    }
		});
	}else{
		$('#SideVqPqList').empty();
		updateVqPqSelection(cookiePath, cookieDomain);
	}
	
}

function clickMakeCheckbox(makeObj, cookiePath, cookieDomain){
    var checkStatus = makeObj.checked;
    var checkVal = makeObj.value;

    $('li.leftmenuitem > input[type=checkbox][value='+checkVal+']','#SideMakeList').each(function(){
            this.checked = checkStatus;
            var parentDiv= $(this).parent().find('div.modelList');
	    if(parentDiv.is(':hidden') && checkStatus){
		parentDiv.find('input[type=checkbox]').attr('checked', '');
	    }else{
		parentDiv.find('input[type=checkbox]').attr('checked', checkStatus);
	    }
    });

    updateMakeSelection(cookiePath, cookieDomain);
    FilterBrandCat(cookiePath, cookieDomain);
    
    showVqPq(cookiePath, cookieDomain);
}

function clickModelCheckbox(modelObj, cookiePath, cookieDomain){
    var checkStatus = modelObj.checked;
    var checkVal = modelObj.value;

    $('.modelList input[type=checkbox][value='+checkVal+']','#SideMakeList').each(function(){
            this.checked = checkStatus;
    });
    
    $('.modelList input[type=checkbox][value='+checkVal+']','#SideMakeList').each(function(){
            var makeNode = $(this).parent().parent();
            var makeCheckbox = makeNode.parent().parent().find('input[type=checkbox]:first');
            if($('input[type=checkbox]:checked', makeNode).length > 0){
                    makeCheckbox.attr('checked', 'checked');
            }else{
                    makeCheckbox.attr('checked', '');
            }
            $('li.leftmenuitem > input[type=checkbox][value='+makeCheckbox.val()+']','#SideMakeList')
                      .attr('checked', makeCheckbox.attr('checked'));
    });

    updateMakeSelection(cookiePath, cookieDomain);
    FilterBrandCat(cookiePath, cookieDomain);
    
    showVqPq(cookiePath, cookieDomain);
}

function clickYearCheckbox(yearObj, cookiePath, cookieDomain){
    updateYearSelection(cookiePath, cookieDomain);
    FilterBrandCat(cookiePath, cookieDomain);
    
    showVqPq(cookiePath, cookieDomain);
}

function clickVqPqCheckbox(vppqObj, cookiePath, cookieDomain){
    updateVqPqSelection(cookiePath, cookieDomain);
}

function clickBrandCheckbox(brandObj, cookiePath, cookieDomain){
    var checkStatus = brandObj.checked;
    var checkVal = brandObj.value;

    $('li.leftmenuitem > input[type=checkbox][value='+checkVal+']','#SideBrandList').each(function(){
            this.checked = checkStatus;
            var parentDiv= $(this).parent().find('div.seriesList');
	    if(parentDiv.is(':hidden') && checkStatus){
		parentDiv.find('input[type=checkbox]').attr('checked', '');
	    }else{
		parentDiv.find('input[type=checkbox]').attr('checked', checkStatus);
	    }
    });

    if($(brandObj).hasClass('moreItem'))
	updateBrandSelection(cookiePath, cookieDomain, true);
    else
	updateBrandSelection(cookiePath, cookieDomain);
	
    showVqPq(cookiePath, cookieDomain);
}

function clickSeiresCheckbox(sereisObj, cookiePath, cookieDomain){
    var checkStatus = sereisObj.checked;
    var checkVal = sereisObj.value;
    var brandObj = $(sereisObj).parent().parent().parent().parent().find('input[type=checkbox]:first');
    
    $('input[type=checkbox][value='+checkVal+']', 'ul.SubcatList').each(function(){
            this.checked = checkStatus;
    });

    $('.seriesList input[type=checkbox][value='+checkVal+']','#SideBrandList').each(function(){
            this.checked = checkStatus;
    });
    
    $('.seriesList input[type=checkbox][value='+checkVal+']','#SideBrandList').each(function(){
            var brandNode = $(this).parent().parent();
            var brandCheckbox = brandNode.parent().parent().find('input[type=checkbox]:first');
            if($('input[type=checkbox]:checked', brandNode).length > 0){
                    brandCheckbox.attr('checked', 'checked');
            }else{
                    brandCheckbox.attr('checked', '');
            }
            $('li.leftmenuitem > input[type=checkbox][value='+brandCheckbox.val()+']','#SideBrandList')
                      .attr('checked', brandCheckbox.attr('checked'));
    });

    if(brandObj.hasClass('moreItem'))
	updateBrandSelection(cookiePath, cookieDomain, true);
    else
	updateBrandSelection(cookiePath, cookieDomain);
	
    showVqPq(cookiePath, cookieDomain);
}

function clickCategoryCheckbox(catObj, cookiePath, cookieDomain){
    var checkStatus = catObj.checked;
    var checkVal = catObj.value;

    $('li.leftmenuitem > input[type=checkbox][value='+checkVal+']','#SideCategoryList').each(function(){
            this.checked = checkStatus;
            var parentDiv= $(this).parent().find('div.subcategoryList');
	    if(parentDiv.is(':hidden') && checkStatus){
		parentDiv.find('input[type=checkbox]').attr('checked', '');
	    }else{
		parentDiv.find('input[type=checkbox]').attr('checked', this.checked);
	    }
    });
    
    if($(catObj).hasClass('moreItem'))
	updateCatSelection(cookiePath, cookieDomain, true);
    else
	updateCatSelection(cookiePath, cookieDomain);
	
    showVqPq(cookiePath, cookieDomain);
}

function clickSubcategoryCheckbox(subcatObj, cookiePath, cookieDomain){
    var checkStatus = subcatObj.checked;
    var checkVal = subcatObj.value;
    var catObj = $(subcatObj).parent().parent().parent().parent().find('input[type=checkbox]:first');
    
    $('input[type=checkbox][value='+checkVal+']', 'ul.SubcatList').each(function(){
            this.checked = checkStatus;
    });

    $('.subcategoryList input[type=checkbox][value='+checkVal+']','#SideCategoryList').each(function(){
            this.checked = checkStatus;
    });
    
    $('.subcategoryList input[type=checkbox][value='+checkVal+']','#SideCategoryList').each(function(){
            var catNode = $(this).parent().parent();
            var catCheckbox = catNode.parent().parent().find('input[type=checkbox]:first');
    
            if($('input[type=checkbox]:checked', catNode).length > 0){
                    catCheckbox.attr('checked', 'checked');
            }else{
                    catCheckbox.attr('checked', '');
            }
            $('li.leftmenuitem > input[type=checkbox][value='+catCheckbox.val()+']','#SideCategoryList')
                      .attr('checked', catCheckbox.attr('checked'));
    });

    if(catObj.hasClass('moreItem'))
	updateCatSelection(cookiePath, cookieDomain, true);
    else
	updateCatSelection(cookiePath, cookieDomain);
	
    showVqPq(cookiePath, cookieDomain);
}

function htmlspecialchars(str){
	if (typeof(str) == "string") {
		str = str.replace(/&/g, "&amp;"); /* must do &amp; first */
		str = str.replace(/"/g, "&quot;");
		str = str.replace(/'/g, "&#039;");
		str = str.replace(/</g, "&lt;");
		str = str.replace(/>/g, "&gt;");
	}
	
        return str;
}

function htmlspecialchars_decode(str){
	if (typeof(str) == "string") {
		str = str.replace(/&quot;/g, "\"");
		str = str.replace(/&#039;/g, "'");
		str = str.replace(/&lt;/g, "<");
		str = str.replace(/&gt;/g, ">");
		str = str.replace(/&amp;/g, "&"); /* must do &amp; last */
	}
	
        return str;
}

function GenerateSelectionStr(obj){
	var strArr = [];
	for(var p in obj){ 
	  if(typeof(obj[p])!="function"){
	      var temp = "";
	      if(obj[p].length>0){
		var subStr = '(';
		var subArr = [];
		$.each(obj[p], function(){
		    subArr.push("<label>" + this + "</label><a href='javascript:void(0)' title='"+ p +"' class='deleteSelectedItem'>&nbsp;&nbsp;&nbsp;&nbsp;</a>");
		});
		subStr += subArr.join(', ') + ')';
		temp = p + subStr;
	      }
	      else{
	        temp = "<label>" + p + "</label><a href='javascript:void(0)' title='"+ p +"' class='deleteSelectedItem'>&nbsp;&nbsp;&nbsp;&nbsp;</a>";
	      }
	      strArr.push(temp);
	  }
	}
	
	return strArr.join(', ');
}

function toggleMake(obj, cookiePath, cookieDomain){
    var parentNode = $(obj).parent();
    var clickImg = parentNode.find('img').attr('src');
    var contentDiv = parentNode.find('div.modelList');
    var checkbox = parentNode.find('input[type=checkbox]');
    if(clickImg.indexOf('plus') != -1){
	var make = MakeURLSafe(parentNode.find('input[type=checkbox]').val());
	var year = [];
	$('input[type=checkbox]:checked', '#SideYearList').each(function(){
	  year.push(this.value);
	});
	var checkState = parentNode.find('input[type=checkbox]').attr('checked');
	
	if(contentDiv.is(":empty")){
		$.ajax({
			url: '/remote.php?w=getmodelsbymake',
			type: 'GET', 
			cache: false,
			dataType: 'text',
			data: { 'make': make, 'year': year.join('_')},
			error: function(){
			//  alert('Error loading XML document');
			},
			success: function(data)
			{
				  contentDiv.html(data);
	    
				  parentNode.find('img:first').attr('src', '/images/minus.gif');
				  parentNode.find('li:last').css({
								   'border':'none',
								   'background':'url(/images/dot_tree.gif) -1px 0 no-repeat',
								   'padding-left': '8px'
								});
				  parentNode.find('li:last').find('img:first').remove();
			  
				  var selectedModels = [];
				  var selectModelStr = getCwCookie('last_search_selection[model]');
				  var modelStr = $.trim(selectModelStr);
				  selectedModels = modelStr.split('_');
	    
				  var selectedMakes = [];
				  var selectMakeStr = getCwCookie('last_search_selection[make]');
				  var makeStr = $.trim(selectMakeStr);
				  selectedMakes = makeStr.split('_');
			  
				  contentDiv.find('input[type=checkbox]').each(function(){		
	    
					  if($.inArray(this.value, selectedModels) != -1){
					      this.checked = 'checked';
					  }else{
					      this.checked = '';
					  }
				    
				  });
				  
				  if(contentDiv.text() == ''){
					if($(obj).find('img').length == 0){
						checkbox.attr('checked', !checkbox.attr('checked'));
						clickMakeCheckbox(checkbox.get(0), cookiePath, cookieDomain);
					}
				  }else{
					contentDiv.slideDown("low");
				  }
			}
		});
	}else{
		parentNode.find('img:first').attr('src', '/images/minus.gif');
		if(contentDiv.text() == ''){
			if($(obj).find('img').length == 0){
				checkbox.attr('checked', !checkbox.attr('checked'));
				clickMakeCheckbox(checkbox.get(0), cookiePath, cookieDomain);
			}
		}else{
			contentDiv.slideDown("low");
		}
	}
    }else{
	parentNode.find('img:first').attr('src', '/images/plus.gif');
	if(!contentDiv.is(":empty") && contentDiv.text() == ''){
		if($(obj).find('img').length == 0){
			checkbox.attr('checked', !checkbox.attr('checked'));
			clickMakeCheckbox(checkbox.get(0), cookiePath, cookieDomain);
		}
	}else{
		contentDiv.slideUp("low");
	}
    }
}

function toggleBrand(obj, cookiePath, cookieDomain){
    var parentNode = $(obj).parent();
    var clickImg = parentNode.find('img').attr('src');
    var contentDiv = parentNode.find('div.seriesList');
    var checkbox = parentNode.find('input[type=checkbox]');
    if(clickImg.indexOf('plus') != -1){
	var brandId = parentNode.find('input[type=checkbox]').val();
	var checkState = parentNode.find('input[type=checkbox]').attr('checked');
	
	if(contentDiv.is(":empty")){
		$.ajax({
		      url: '/remote.php?w=getseriesbybrand',
		      type: 'GET', 
		      cache: false,
		      dataType: 'text',
		      data: { 'brandId': brandId},
		      error: function(){
		      //  alert('Error loading XML document');
		      },
		      success: function(data)
		      {
				contentDiv.html(data);
	  
				parentNode.find('img:first').attr('src', '/images/minus.gif');
				parentNode.find('li:last').css({
								   'border':'none',
								   'background':'url(/images/dot_tree.gif) -1px 0 no-repeat',
								   'padding-left': '8px'
								});
				parentNode.find('li:last').find('img:first').remove();
			
				var selectedSeries = [];
				var selectSeriesStr = getCwCookie('last_search_selection[series]');
				var seriesStr = $.trim(selectSeriesStr);
				selectedSeries = seriesStr.split('_');
	  
				var selectedBrands = [];
				var selectBrandStr = getCwCookie('last_search_selection[brand]');
				var brandStr = $.trim(selectBrandStr);
				selectedBrands = brandStr.split('_');
			
				contentDiv.find('input[type=checkbox]').each(function(){		
	  
					if($.inArray(this.value, selectedSeries) != -1){
					    this.checked = 'checked';
					}else{
					    this.checked = '';
					}
				  
				});
				
				if(contentDiv.text() == ''){
					if($(obj).find('img').length == 0){
						checkbox.attr('checked', !checkbox.attr('checked'));
						clickBrandCheckbox(checkbox.get(0), cookiePath, cookieDomain);
					}
				}else{
					contentDiv.slideDown("low");
				}
			}
		});
	}else{
		parentNode.find('img:first').attr('src', '/images/minus.gif');
		if(contentDiv.text() == ''){
			if($(obj).find('img').length == 0){
				checkbox.attr('checked', !checkbox.attr('checked'));
				clickBrandCheckbox(checkbox.get(0), cookiePath, cookieDomain);
			}
		}else{
			contentDiv.slideDown("low");
		}
	}
    }else{
	parentNode.find('img:first').attr('src', '/images/plus.gif');
	if(!contentDiv.is(":empty") && contentDiv.text() == ''){
		if($(obj).find('img').length == 0){
			checkbox.attr('checked', !checkbox.attr('checked'));
			clickBrandCheckbox(checkbox.get(0), cookiePath, cookieDomain);
		}
	}else{
		contentDiv.slideUp("low");
	}
    }
}

function toggleCategory(obj, cookiePath, cookieDomain){
    var parentNode = $(obj).parent();
    var clickImg = parentNode.find('img').attr('src');
    var contentDiv = parentNode.find('div.subcategoryList');
    var checkbox = parentNode.find('input[type=checkbox]');
    if(clickImg.indexOf('plus') != -1){
	var catId = parentNode.find('input[type=checkbox]').val();
	var checkState = parentNode.find('input[type=checkbox]').attr('checked');
	
	if(contentDiv.is(":empty")){
		$.ajax({
			url: '/remote.php?w=getSubcatByCat',
			type: 'GET', 
			cache: false,
			dataType: 'text',
			data: { 'catId': catId},
			error: function(){
			//  alert('Error loading XML document');
			},
			success: function(data)
			{
				contentDiv.html(data);
	    
				parentNode.find('img:first').attr('src', '/images/minus.gif');
				parentNode.find('li:last').css({
								   'border':'none',
								   'background':'url(/images/dot_tree.gif) -1px 0 no-repeat',
								   'padding-left': '8px'
								});
				parentNode.find('li:last').find('img:first').remove();
			
				var selectedSubcat = [];
				var selectSubcatStr = getCwCookie('last_search_selection[subcategory]');
				var subcatStr = $.trim(selectSubcatStr);
				selectedSubcat = subcatStr.split('_');
	    
				var selectedCat = [];
				var selectCatStr = getCwCookie('last_search_selection[category]');
				var catStr = $.trim(selectCatStr);
				selectedCat =catStr.split('_');
			
				contentDiv.find('input[type=checkbox]').each(function(){		
				    
					if($.inArray(this.value, selectedSubcat) != -1){
					    this.checked = 'checked';
					}else{
					    this.checked = '';
					}
				    
				});
				
				if(contentDiv.text() == ''){
					if($(obj).find('img').length == 0){
						checkbox.attr('checked', !checkbox.attr('checked'));
						clickCategoryCheckbox(checkbox.get(0), cookiePath, cookieDomain);
					}
				}else{
					contentDiv.slideDown("low");
				}
			}
		});
	}else{
		parentNode.find('img:first').attr('src', '/images/minus.gif');
		if(contentDiv.text() == ''){
			if($(obj).find('img').length == 0){
				checkbox.attr('checked', !checkbox.attr('checked'));
				clickCategoryCheckbox(checkbox.get(0), cookiePath, cookieDomain);
			}
		}else{
			contentDiv.slideDown("low");
		}
	}
    }else{
	parentNode.find('img:first').attr('src', '/images/plus.gif');	
	if(!contentDiv.is(":empty") && contentDiv.text() == ''){
		if($(obj).find('img').length == 0){
			checkbox.attr('checked', !checkbox.attr('checked'));
			clickCategoryCheckbox(checkbox.get(0), cookiePath, cookieDomain);
		}
	}else{
		contentDiv.slideUp("low");
	}
    }
    
}

function ClearSelectionCookie(cookiePath, cookieDomain){
	deleteCwCookie('last_search_selection[year]', cookiePath, cookieDomain);
	deleteCwCookie('last_search_selection[make]', cookiePath, cookieDomain);
	deleteCwCookie('last_search_selection[model]', cookiePath, cookieDomain);
	deleteCwCookie('last_search_selection[brand]', cookiePath, cookieDomain);
	deleteCwCookie('last_search_selection[series]', cookiePath, cookieDomain);
	deleteCwCookie('last_search_selection[category]', cookiePath, cookieDomain);
	deleteCwCookie('last_search_selection[subcategory]', cookiePath, cookieDomain);
}

function addslashes(str){
	return (str+'').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}

function MakeURLSafe(str)
{
	str = str.replace(new RegExp("-", "gm"), "%2d");
	str = str.replace(new RegExp("\\+", "gm"), "%2b");
	str = str.replace(new RegExp("\\+", "gm"), "%2b");
	str = str.replace(new RegExp("\\/", "gm"), "{47}");
	str = urlencode(str);
	str = str.replace(new RegExp("\\+", "gm"), "-");
    return str;
}

function MakeURLNormal(str)
{
	str = str.replace(new RegExp("-", "gm"), " ");
	str = urldecode(str);
	str = str.replace(new RegExp("\\{47\\}", "gm"), "/");
    str = str.replace(new RegExp("%2d", "gm"), "-");
    str = str.replace(new RegExp("%2b", "gm"), "+");

    return str;
}

function urlencode(str) 
{
	str = (str+'').toString();
	return encodeURIComponent(str).replace(/!/g, '%21')
															.replace(/'/g, '%27')
															.replace(/\(/g, '%28')
															.replace(/\)/g, '%29')
                                                            .replace(/\*/g, '%2A')
                                                            .replace(/%20/g, '+');
}

function urldecode (str) 
{
    return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}

function getCwCookie( name ) {

	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return '';
	}
	
	if ( start == -1 ) return '';
	
	var end = document.cookie.indexOf( ';', len );
	
	if ( end == -1 ) 
		end = document.cookie.length;
	
	return urldecode(document.cookie.substring( len, end ));

}

 

function setCwCookie( name, value, expires, path, domain, secure ) {

	var today = new Date();
	
	today.setTime( today.getTime() );
	
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name+'='+ urlencode(value) + 
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + 
		( ( path ) ? ';path=' + path : ';path=/' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );

}

 

function deleteCwCookie( name, path, domain ) {

	if ( getCwCookie( name ) ) 
		document.cookie = name + '=' + 
			( ( path ) ? ';path=' + path : ';path=/') + 
			( ( domain ) ? ';domain=' + domain : '' ) + ';expires=Thu, 01-Jan-1970 00:00:01 GMT';

} 

// Fetch the value of a cookie
function get_cookie(name) {
	name = name += "=";
	var cookie_start = document.cookie.indexOf(name);
	if(cookie_start > -1) {
		cookie_start = cookie_start+name.length;
		cookie_end = document.cookie.indexOf(';', cookie_start);
		if(cookie_end == -1) {
			cookie_end = document.cookie.length;
		}
		return unescape(document.cookie.substring(cookie_start, cookie_end));
	}
}

// Set a cookie
function set_cookie(name, value, expires)
{
	if(!expires) {
		expires = "; expires=Wed, 1 Jan 2020 00:00:00 GMT;"
	} else {
		expire = new Date();
		expire.setTime(expire.getTime()+(expires*1000));
		expires = "; expires="+expire.toGMTString();
	}
	document.cookie = name+"="+escape(value)+expires;
}

/* Javascript functions for the products page */
var num_products_to_compare = 0;
var product_option_value = "";

function showProductImage(filename, product_id) {
	var l = (screen.availWidth/2)-350;
	var t = (screen.availHeight/2)-300;
	var variationAdd = '';
	if($('body').attr('currentVariation') != '' && typeof($('body').attr('currentVariation')) != "undefined") {
		variationAdd = '&variation_id='+$('body').attr('currentVariation');
	}
	window.open(filename + "?product_id="+product_id+variationAdd, "imagePop", "toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=700,height=600,top="+t+",left="+l);
}

function showProductImageNew(filename, product_id, cur_no) {

    var l = ((screen.availWidth - 800)/2);
    var t = ((screen.availHeight - 650)/2);
    var variationAdd = '';
    if($('body').attr('currentVariation') != '' && typeof($('body').attr('currentVariation')) != "undefined") {
        variationAdd = '&variation_id='+$('body').attr('currentVariation');
    }      
    window.open(filename + ""+"#"+cur_no, "imagePop", "toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=800,height=650,top="+t+",left="+l);
   //window.open(filename + "?product_id="+product_id+variationAdd+"#"+cur_no, "imagePop", "toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=800,height=650,top="+t+",left="+l);
}

function showProductVideoNew(filename, product_id) {
    var l = ((screen.availWidth - 550)/2);
    var t = ((screen.availHeight - 400)/2);
    var variationAdd = '';
    if($('body').attr('currentVariation') != '' && typeof($('body').attr('currentVariation')) != "undefined") {
        variationAdd = '&variation_id='+$('body').attr('currentVariation');
    }
    //window.open(filename + "?product_id="+product_id+variationAdd, "videoPop", "toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=550,height=400,top="+t+",left="+l);
    window.open(filename, "videoPop", "toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=550,height=400,top="+t+",left="+l); 
}

function CheckProductConfigurableFields(form)
{
	var requiredFields = $('.FieldRequired');
	var valid = true;
	requiredFields.each(function() {
		var namePart = this.name.replace(/^.*\[/, '');
		var fieldId = namePart.replace(/\].*$/, '');

		if(this.type=='checkbox' ) {
			if(!this.checked) {
				valid = false;
				alert(lang.EnterRequiredField);
				this.focus();
				this.select();
				return false;
			}
		} else if(this.value == '') {
			if(this.type != 'file' || (this.type == 'file' && document.getElementById('CurrentProductFile_'+fieldId).value == '')) {
				valid = false;
				alert(lang.EnterRequiredField);
				this.focus();
				this.select();
				return false;
			}
		}
	});

	var fileFields = $(form).find('input[type=file]');
	fileFields.each(function() {
		if(this.value != '') {
			var namePart = this.name.replace(/^.*\[/, '');
			var fieldId = namePart.replace(/\].*$/, '');
			var fileTypes = document.getElementById('ProductFileType_'+fieldId).value;

			fileTypes = ','+fileTypes.replace(' ', '').toLowerCase()+','
			var ext = this.value.replace(/^.*\./, '').toLowerCase();

			if(fileTypes.indexOf(','+ext+',') == -1) {
				alert(lang.InvalidFileTypeJS);
				this.focus();
				this.select();
				valid = false;
			}

		}
	});

	return valid;
}

function check_add_to_cart(form, required, retailMode, inventory) {
	if(retailMode && retailMode==1){
		alert('Please turn off the retail mode to add products into the shopping cart.');
		return false;
	}
	
	if(retailMode && retailMode==-1){
		return false;
	}
	
	if(retailMode && retailMode==-2){
		alert('Sorry, there is no inventory for this product.');
		return false;
	}
	
	if($('.quantityInput').val() > inventory){
		alert('Sorry, the inventory is not enough.');
		return false;
	}
	
	var valid = true;
	var qtyInputs = $(form).find('input.qtyInput');
	qtyInputs.each(function() {
		if(isNaN($(this).val()) || $(this).val() <= 0) {
			alert(lang.InvalidQuantity);
			this.focus();
			this.select();
			valid = false;
			return false;
		}
	});
	if(valid == false) {
		return false;
	}

	if(!CheckProductConfigurableFields(form)) {
		return false;
	}

	if(required && !$(form).find('.CartVariationId').val()) {
		alert(lang.OptionMessage);
		var select = $(form).find('select').get(0);
		if(select) {
			select.focus();
		}
		var radio = $(form).find('input[type=radio]').get(0);
		if(radio) {
			radio.focus();
		}
		return false;
	}

	if (!CheckEventDate()) {
		return false;
	}

	return true;
}

function compareProducts(compare_path) {
	var pids = "";

	if($('form').find('input[name=compare_product_ids][checked]').size() >= 2) {
		var cpids = document.getElementsByName('compare_product_ids');

		for(i = 0; i < cpids.length; i++) {
			if(cpids[i].checked)
				pids = pids + cpids[i].value + "/";
		}

		pids = pids.replace(/\/$/, "");
		document.location.href = compare_path + pids;
		return false;
	}
	else {
		alert(lang.CompareSelectMessage);
		return false;
	}
}

function product_comparison_box_changed(state) {
	// Increment num_products_to_compare - needs to be > 0 to submit the product comparison form


	if(state)
		num_products_to_compare++;
	else
		if (num_products_to_compare != 0)
			num_products_to_compare--;
}

function remove_product_from_comparison(id) {
	if(num_compare_items > 2) {
		for(i = 1; i < 11; i++) {
			document.getElementById("compare_"+i+"_"+id).style.display = "none";
		}

		num_compare_items--;
	}
	else {
		alert(lang.CompareTwoProducts);
	}
}

function show_product_review_form() {
	document.getElementById("rating_box").style.display = "";
	document.location.href = "#write_review";
}

function jump_to_product_reviews() {
	document.location.href = "#reviews";
}

function g(id) {
	return document.getElementById(id);
}

function check_product_review_form() {
	var revrating = g("revrating");
	var revtitle = g("revtitle");
	var revtext = g("revtext");
	var revfromname = g("revfromname");
	var captcha = g("captcha");

	if(revrating.selectedIndex == 0) {
		alert(lang.ReviewNoRating);
		revrating.focus();
		return false;
	}

	if(revtitle.value == "") {
		alert(lang.ReviewNoTitle);
		revtitle.focus();
		return false;
	}

	if(revtext.value == "") {
		alert(lang.ReviewNoText);
		revtext.focus();
		return false;
	}

	if(captcha.value == "" && HideReviewCaptcha != "none") {
		alert(lang.ReviewNoCaptcha);
		captcha.focus();
		return false;
	}

	return true;
}
/*
function check_small_search_form() {
	var search_query = g("search_query");

	if(search_query.value == "") {
		alert(lang.EmptySmallSearch);
		search_query.focus();
		return false;
	}

	return true;
}
*/
function setCurrency(currencyId)
{
	var gotoURL = location.href;

	if (location.search !== '')
	{
		if (gotoURL.search(/[&|\?]setCurrencyId=[0-9]+/) > -1)
			gotoURL = gotoURL.replace(/([&|\?]setCurrencyId=)[0-9]+/, '$1' + currencyId);
		else
			gotoURL = gotoURL + '&setCurrencyId=' + currencyId;
	}
	else
		gotoURL = gotoURL + '?setCurrencyId=' + currencyId;

	location.href = gotoURL;
}


// Dummy sel_panel function for when design mode isn't enabled
function sel_panel(id) {}

function inline_add_to_cart(filename, product_id, quantity, returnTo) {
	if(typeof(quantity) == 'undefined') {
		quantity = '1';
	}
	var html = '<form action="' + filename + '/cart.php" method="post" id="inlineCartAdd">';
	if(typeof(returnTo) != 'undefined' && returnTo == true) {
		var returnLocation = window.location;
		html += '<input type="hidden" name="returnUrl" value="'+escape(returnLocation)+'" />';
	}
	html += '<input type="hidden" name="action" value="add" />';
	html += '<input type="hidden" name="qty" value="'+quantity+'" />';
	html += '<input type="hidden" name="product_id" value="'+product_id+'" />';
	html += '<\/form>';
   $('body').append(html);
   $('#inlineCartAdd').submit();
}


// Dummy JS object to hold language strings.
var lang = {
};

// IE 6 doesn't support the :hover selector on elements other than links, so
// we use jQuery to work some magic to get our hover styles applied.
if(document.all) {
	var isIE7 = /*@cc_on@if(@_jscript_version>=5.7)!@end@*/false;
	if(isIE7 == false) {
		$(document).ready(function() {
			$('.ProductList li').hover(function() {
				$(this).addClass('Over');
			},
			function() {
				$(this).removeClass('Over');
			});
			$('.ComparisonTable tr').hover(function() {
				$(this).addClass('Over');
			},
			function() {
				$(this).removeClass('Over');
			});
		});
	}
	$('.ProductList li:last-child').addClass('LastChild');
}

function tooltip(path,id) { 
    $('#'+id).tooltip({ 
	showURL: false, 
	bodyHandler: function() {
	    return $("<img>").attr("src", path);
	} 
    });
}

function ShowCompDesc(sku,id) 
{
	var item = $('#'+id);
    if(item.attr('checked'))    {       
	$('#compqty_'+item.val()).show();
		$('#pr_'+item.val()).show();
    }
    else    {            
	$('#compqty_'+item.val()).hide();
	$('#pr_'+item.val()).hide();			
    }
	var path = config.ShopPath + '/templates/default/images/small_pluscart.gif'
	var img = "<img src='"+path+"' id='tImage' />"
	var hidVal = $('#hid_'+id).val()
	var tabval = img + hidVal
	if(item.attr('checked'))    {
		$('#CompItem_Tab > a').html(tabval)

		var phpUrl = config.ShopPath + '/complementarydesc.php';
		$.ajax(
		{
			url: phpUrl,
			type: 'GET', 
			cache: false,
			dataType: 'text',
			data: { prodsku: sku},
			error: function(){
			},
			success: function(data)
			{   
				$('#CompItem').html(data);

			}
		}
		);
	}
}

function GetSearchCondition(){
	var searchParam = '';

        var Brands = [], Series = [], Categories = [], Subcategories = [], Years=[], Makes=[], Models=[];
        var cookieBrand = getCwCookie('last_search_selection[brand]');
        var cookieSeries = getCwCookie('last_search_selection[series]');
        var cookieCategory = getCwCookie('last_search_selection[category]');
        var cookieSubcategory = getCwCookie('last_search_selection[subcategory]');
        var cookieYear = getCwCookie('last_search_selection[year]');
        var cookieMake = getCwCookie('last_search_selection[make]');
        var cookieModel = getCwCookie('last_search_selection[model]');
        
        if($.trim(cookieBrand).length>0)
		Brands = cookieBrand.split('_');
        if($.trim(cookieSeries).length>0)
		Series = cookieSeries.split('_');
        if($.trim(cookieCategory).length>0)
        	Categories = cookieCategory.split('_');
        if($.trim(cookieSubcategory).length>0)
        	Subcategories = cookieSubcategory.split('_');
        if($.trim(cookieYear).length>0)
        	Years = cookieYear.split('_');
        if($.trim(cookieMake).length>0)
        	Makes = cookieMake.split('_');
        if($.trim(cookieModel).length>0)
        	Models = cookieModel.split('_');
		
	Brands.unique();
	Series.unique();
	Categories.unique();
	Subcategories.unique();
	Years.unique();
	Makes.unique();
	Models.unique();

    	if(Years.length>0)
    		searchParam += '/year/'+Years.join('_');
    	if(Makes.length>0)
    		searchParam += '/make/'+MakeURLSafe(Makes.join('_'));
    	if(Models.length>0)
    		searchParam += '/model/'+MakeURLSafe(Models.join('_'));
    	if(Brands.length>0)
    		searchParam += '/brand/'+Brands.join('_');
    	if(Series.length>0)
    		searchParam += '/series/'+Series.join('_');
    	if(Categories.length>0)
    		searchParam += '/category/'+Categories.join('_');
    	if(Subcategories.length>0)
    		searchParam += '/subcategory/'+Subcategories.join('_');
	
	return searchParam;	
}

function ShowNewsiteInstruction(){
	var yearText = '', makeText = '', modelText = '', brandText = '', categoryText = '';
	yearText = $.trim($('#side_selected_year').text());
	makeText = $.trim($('#side_selected_make').text());
	modelText = $.trim($('#side_selected_model').text());
	brandText = $.trim($('#side_selected_brand').text());
	categoryText = $.trim($('#side_selected_category').text());
	
	if(yearText.length == 0 &&
	   makeText.length == 0 &&
	   modelText.length == 0 &&
	   brandText.length == 0 &&
	   categoryText.length == 0
	){
		$('#NewSiteMsgBox').show();
	}else{
		$('#NewSiteMsgBox').hide();
	}
}

function chksubmit() 
{
}
//johnny add for change captcha
function ChangeCaptcha(){
	var phpUrl = config.ShopPath + '/getcaptcha.php';
	$.ajax({
		url: phpUrl,
		type: 'GET',
		cache: 'false',
		dateType: 'text',
		error: function(){
			// error message
		},
		success: function(data){
			$("#captchaImg").attr("src", data);
		}
	});
}

var config = {};
$(document).ready(function() {
	$('.InitialFocus').focus();
	$('table.Stylize tr:first-child').addClass('First');
	$('table.Stylize tr:last-child').addClass('Last');
	$('table.Stylize tr td:odd').addClass('Odd');
	$('table.Stylize tr td:even').addClass('Even');
	$('table.Stylize tr:even').addClass('Odd');
	$('table.Stylize tr:even').addClass('Even');

	$('.TabContainer .TabNav li').click(function() {
		$(this).parent('.TabNav').find('li').removeClass('Active');
		$(this).parents('.TabContainer').find('.TabContent').hide();
		$(this).addClass('Active');
		$(this).parents('.TabContainer').find('#TabContent'+this.id).show();
		$(this).find('a').blur();
		return false;
	});
	
	$(".CategoryImage img", "#HomeFeaturedProducts").css("cursor", "pointer");
	
	// add ymm selection when user click brand or category on home page
	$(".CategoryImage a", "#tc-static-featured-brands").click(function(){
            var localLink = $(this).attr("href");
            if(getCwCookie("last_search_selection[year]") != "")
		$(this).attr("href", localLink += "/year/" + getCwCookie("last_search_selection[year]"));
	    if(getCwCookie("last_search_selection[model]") != "")
		$(this).attr("href", localLink += "/model/" + getCwCookie("last_search_selection[model]"));
	    if(getCwCookie("last_search_selection[make]") != "")
		$(this).attr("href", localLink += "/make/" + getCwCookie("last_search_selection[make]"));
	    if(getCwCookie("last_search_selection[category]") != "")
		$(this).attr("href", localLink += "/category/" + getCwCookie("last_search_selection[category]"));
	    if(getCwCookie("last_search_selection[subcategory]") != "")
		$(this).attr("href", localLink += "/subcategory/" + getCwCookie("last_search_selection[subcategory]"));
        });
	$(".CategoryDetails a", "#tc-static-featured-brands").click(function(){
	    var localLink = $(this).attr("href");
            if(getCwCookie("last_search_selection[year]") != "")
		$(this).attr("href", localLink += "/year/" + getCwCookie("last_search_selection[year]"));
	    if(getCwCookie("last_search_selection[model]") != "")
		$(this).attr("href", localLink += "/model/" + getCwCookie("last_search_selection[model]"));
	    if(getCwCookie("last_search_selection[make]") != "")
		$(this).attr("href", localLink += "/make/" + getCwCookie("last_search_selection[make]"));
	    if(getCwCookie("last_search_selection[category]") != "")
		$(this).attr("href", localLink += "/category/" + getCwCookie("last_search_selection[category]"));
	    if(getCwCookie("last_search_selection[subcategory]") != "")
		$(this).attr("href", localLink += "/subcategory/" + getCwCookie("last_search_selection[subcategory]"));
	});
	
	$(".CategoryImage img", "#HomeFeaturedProducts").click(function(){
	    var localLink = $(this).parent().next().find("a").attr("href");
	    if(getCwCookie("last_search_selection[year]") != "")
		$(this).attr("href", localLink += "/year/" + getCwCookie("last_search_selection[year]"));
	    if(getCwCookie("last_search_selection[model]") != "")
		$(this).attr("href", localLink += "/model/" + getCwCookie("last_search_selection[model]"));
	    if(getCwCookie("last_search_selection[make]") != "")
		$(this).attr("href", localLink += "/make/" + getCwCookie("last_search_selection[make]"));
	    if(getCwCookie("last_search_selection[brand]") != "")
		$(this).attr("href", localLink += "/brand/" + getCwCookie("last_search_selection[brand]"));
	    if(getCwCookie("last_search_selection[series]") != "")
		$(this).attr("href", localLink += "/series/" + getCwCookie("last_search_selection[series]"));
	    window.location = localLink;
	});
	
	$(".CategoryImage a", "#HomeFeaturedProducts").click(function(){
	    var localLink = $(this).attr("href");
	    if(getCwCookie("last_search_selection[year]") != "")
		$(this).attr("href", localLink += "/year/" + getCwCookie("last_search_selection[year]"));
	    if(getCwCookie("last_search_selection[model]") != "")
		$(this).attr("href", localLink += "/model/" + getCwCookie("last_search_selection[model]"));
	    if(getCwCookie("last_search_selection[make]") != "")
		$(this).attr("href", localLink += "/make/" + getCwCookie("last_search_selection[make]"));
	    if(getCwCookie("last_search_selection[brand]") != "")
		$(this).attr("href", localLink += "/brand/" + getCwCookie("last_search_selection[brand]"));
	    if(getCwCookie("last_search_selection[series]") != "")
		$(this).attr("href", localLink += "/series/" + getCwCookie("last_search_selection[series]"));
	});
	$(".CategoryDetails a", "#HomeFeaturedProducts").click(function(){
	    var localLink = $(this).attr("href");
	    if(getCwCookie("last_search_selection[year]") != "")
		$(this).attr("href", localLink += "/year/" + getCwCookie("last_search_selection[year]"));
	    if(getCwCookie("last_search_selection[model]") != "")
		$(this).attr("href", localLink += "/model/" + getCwCookie("last_search_selection[model]"));
	    if(getCwCookie("last_search_selection[make]") != "")
		$(this).attr("href", localLink += "/make/" + getCwCookie("last_search_selection[make]"));
	    if(getCwCookie("last_search_selection[brand]") != "")
		$(this).attr("href", localLink += "/brand/" + getCwCookie("last_search_selection[brand]"));
	    if(getCwCookie("last_search_selection[series]") != "")
		$(this).attr("href", localLink += "/series/" + getCwCookie("last_search_selection[series]"));
	});
	$(".CategoryImage a", "#tc-static-featured-cats").click(function(){
	    var localLink = $(this).attr("href");
	    if(getCwCookie("last_search_selection[year]") != "")
		$(this).attr("href", localLink += "/year/" + getCwCookie("last_search_selection[year]"));
	    if(getCwCookie("last_search_selection[model]") != "")
		$(this).attr("href", localLink += "/model/" + getCwCookie("last_search_selection[model]"));
	    if(getCwCookie("last_search_selection[make]") != "")
		$(this).attr("href", localLink += "/make/" + getCwCookie("last_search_selection[make]"));
	    if(getCwCookie("last_search_selection[brand]") != "")
		$(this).attr("href", localLink += "/brand/" + getCwCookie("last_search_selection[brand]"));
	    if(getCwCookie("last_search_selection[series]") != "")
		$(this).attr("href", localLink += "/series/" + getCwCookie("last_search_selection[series]"));
	});
	$(".CategoryDetails a", "#tc-static-featured-cats").click(function(){
	    var localLink = $(this).attr("href");
	    if(getCwCookie("last_search_selection[year]") != "")
		$(this).attr("href", localLink += "/year/" + getCwCookie("last_search_selection[year]"));
	    if(getCwCookie("last_search_selection[model]") != "")
		$(this).attr("href", localLink += "/model/" + getCwCookie("last_search_selection[model]"));
	    if(getCwCookie("last_search_selection[make]") != "")
		$(this).attr("href", localLink += "/make/" + getCwCookie("last_search_selection[make]"));
	    if(getCwCookie("last_search_selection[brand]") != "")
		$(this).attr("href", localLink += "/brand/" + getCwCookie("last_search_selection[brand]"));
	    if(getCwCookie("last_search_selection[series]") != "")
		$(this).attr("href", localLink += "/series/" + getCwCookie("last_search_selection[series]"));
	});

});
