/**
 Sets the Analytics Pass Through values of Component Name and Slot Number
 via a Cookie.

 Note: this is required due to SEO restrictions for not being able to pass these
       values via the query string.
*/
function setAnalyticsPassThroughCookie(componentName, productSlot) {

    var cookieVal = '';
    var elem = 0;
    var vals = new Array();

    // componentName
    if (componentName.length > 0) {
        vals[elem] = "ComponentName=" + componentName;
        elem++;
    }

    // slotNumber
    if (productSlot.length > 0) {
        vals[elem] = "ProductSlot=" + productSlot;
        elem++;
    }

    cookieVal = vals.join("&");

    if (cookieVal.length > 0) {
        document.cookie = 'anlytxpt=' + escape(cookieVal) + ";path=/";
    }

}

function setAnalyticsTabsCookie(componentName) {

    var cookieVal = '';
    var today = new Date();
	today.setTime( today.getTime() );

    var expire = new Date();
    expire.setTime(today.getTime() + (60000) );
    // componentName
    if (componentName.length > 0) {
        document.cookie = 'anlytxtab=' + escape(componentName) + "; expires=" + expire.toGMTString()+";path=/ ";
    }
}

function setAnalyticsPassThroughCookieEvent(eventValue) {

    var cookieVal = '';

    if(eventValue.length > 0){
        cookieVal += 'events=' + eventValue;
    }

    if (cookieVal.length > 0) {
        document.cookie = 'anlytxpt=' + escape(cookieVal) + ";path=/";
    }

}

function setAnalyticsMoreTopBrandsCookie(componentName) {

    var cookieVal = '';
    var today = new Date();
	today.setTime( today.getTime() );

    var expire = new Date();
    expire.setTime(today.getTime() + (60000) );
    // componentName
    if (componentName.length > 0) {
        document.cookie = 'anlytxmtb=' + escape(componentName) + "; expires=" + expire.toGMTString()+";path=/ ";
    }
}

function urlencode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'

    var ret = str;

    ret = ret.toString();
    ret = encodeURIComponent(ret);
    ret = ret.replace(/%20/g, '+');

    return ret;
}

function getCompare(f) {
    var R = '';
    var cnt = 0;
    for(var n=0; n<50; n++) {

        var e = document.getElementById("comp"+n);
        if(e != null) {
            if(e.checked) {
                R += e.value + ' ';
                cnt++;
            }
        }
    }
    if(cnt < 2) {
        alert("Please Select at least (2) two products for comparison");
        return false;
    }
    if(R.length > 0) {
        f.R.value = R;
        return true;
    } else {
        return false;
    }
}
function validateChecks(f) {
    var R = '';
    var chkCnt = 0;
    for(var n=0; n<50; n++) {
        var e = document.getElementById("comp"+n);
        if(e != null) {
            if(e.checked) {
                chkCnt++;
            }
        }
        if(chkCnt > 4) {
            alert("You may select up to (4) four products to compare");
            f.checked = false;
            break;
        }
    }
}

function validateSearch(form_name,search_name){
	var Search = document.getElementById(form_name);
	var Ntt = document.getElementById(search_name);
	if(Ntt.value=="" || Ntt.value=="Keyword, category or part number" || Ntt.value=="Enter product name"){
		alert("You must enter a search term");
		return false;
	}
}

function show_ref(type) {
	var Div = document.getElementById(type + "div");
	var Lnk = document.getElementById(type + "lnk");
	var Hide = document.getElementById(type + "hide");
	Div.style.display = '';
	Lnk.style.display = 'none';
	Hide.style.display = '';
}
function hide_ref(type) {
	var Div = document.getElementById(type + "div");
	var Lnk = document.getElementById(type + "lnk");
	var Hide = document.getElementById(type + "hide");
	Div.style.display = 'none';
	Lnk.style.display = '';
	Hide.style.display = 'none';
}
if (typeof($) != "undefined") {
    $(function() {
        var cat_id = 0;
        $("div.cat_li_toggle").each(function() {
            cat_id++;
            var cat_id_id = cat_id;
            $(this).click(function() {
                var el_li 		= document.getElementById("cat_li_id_" + cat_id_id);
                var el_img_li = document.getElementById("img_li_id_" + cat_id_id);
                if (el_li.style.display == 'none') {
                    $(el_li).show();
                    el_img_li.src = el_img_li.src.replace(/plus2/,"minus");
                } else {
                    $(el_li).hide();
                    el_img_li.src = el_img_li.src.replace(/minus/,"plus2");
                }
            });
        });
    });
}



function savequote() {
	document.formbasket.Submit.value = 'Save Quote';
	document.formbasket.submit();
}


function pop_shipping() {
	PositionX = 100;
	PositionY = 100;
	defaultWidth  = 400;
	defaultHeight = 400;
	var opt='resizable=yes,scrollbars=yes,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
	window.open('/popup/?type=shipping','',opt);
}
function popup_genwin(u, n, w, h)
{
	gwin=window.open(u, n, 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=yes,width='+w+',height=' + h);
	gwin.focus();
}
function pop_core() {

	PositionX = 100;
	PositionY = 100;
	defaultWidth  = 400;
	defaultHeight = 400;
	var opt='resizable=yes,scrollbars=yes,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
	window.open('/popupBasket.php?type=core','',opt);

}
// pop new window; used in BML popup link  -alvin 04142007
function core_popup(domain, w) {
	website_window=window.open(domain, 'website_window', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=yes,width='+w+', height=600');
	website_window.focus();
}

function pop_quote() {

	PositionX = 100;
	PositionY = 100;
	defaultWidth  = 300;
	defaultHeight = 300;
	var opt='resizable=yes,scrollbars=yes,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
	window.open('/popupBasket.php?type=quote','',opt);
}
function pop_fax() {
	PositionX = 100;
	PositionY = 100;
	defaultWidth  = 500;
	defaultHeight = 700;
	var opt='resizable=yes,scrollbars=yes';
	window.open('/popupBasket.php?type=fax','',opt);
}
function popitup(url) {
    PositionX = 100;
	PositionY = 100;
	defaultWidth  = 660;
	defaultHeight = 560;
	var urlName=url.split(".");
	var opt='resizable=yes,scrollbars=yes,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
	newwindow=window.open('/popup.php/?type='+urlName[0],'',opt);
	if (window.focus) {newwindow.focus()}
}
function check_saved_vehicle() {
    if (document.forms.savedv.ymm.value == '') {
        alert('Please select a Saved Vehicle');
        return false;
    }
}
//clickfocus
function applyClickFocus(el)
{
	if (typeof (el) == 'string') {
        el = document.getElementById(el);
    }
	if ((!el) || (el.nodeType != 1)) {
        return;
    }
	el.defaultText =
		(el.attributes.value) ? el.attributes.value.nodeValue :
		(el.value)            ? el.value :
		'';
	el.onfocus = function()
	{
		if (this.value == this.defaultText)  { this.value = ''; }
		this.select();
	};
	el.onblur = function()
	{
		if (this.value == '')  { this.value = this.defaultText; }
	};
}
function applyClickFocusToAll()
{
	var els = document.getElementsByTagName('input');
	for (var i=0; i<els.length; ++i)
	{
		el = els[i];
		if ((el.type == "text") && (el.className.match(/\bclickfocus\b/) != null))
			{ applyClickFocus(el); }
	}
}
//feedback
var swidth = screen.width;
var sheight = screen.height;
function feedbackpop(cur_url) {
	var feedback_url = '/feedback/';
	if ((typeof cur_url == "undefined") || (cur_url == ""))
	{
		cur_url = window.location;
	}
	window.open(feedback_url+'?w='+swidth+'&h='+sheight+'&u='+cur_url, 'feedbk', 'width=535, height=488, screenX='+((swidth-535)/2)+',screenY='+((sheight-488)/2)+',top='+((sheight-488)/2)+',left='+((swidth-535)/2)+',resizable=yes,copyhistory=yes,scrollbars=no');
}
function fcheck_required_overall() {
	var OverallValue = "";
	if(typeof document.feedback.overall!='undefined') {
		if(typeof document.feedback.overall.value!='undefined'){
			OverallValue = document.feedback.overall.value;
		} else {
			for (i=0; i<5; i++) {
			  if(typeof document.feedback.overall[i]!='undefined'){
				  if(document.feedback.overall[i].checked=="1"){
					OverallValue=document.feedback.overall[i].value;
				  }
			  }else{OverallValue="0";}
			}
		}

	} else { OverallValue="0"; }
	if (OverallValue == "" ) {
		alert("Please choose an overall rating before submitting.");
		return false;
	}
}
function fcheck_required_comments() {
	var CommentsValue = "";
	if(typeof document.feedback.comments!='undefined') {
		if(typeof document.feedback.comments.value!='undefined'){
			if (document.feedback.comments.value != 'Please enter your comments about this webpage here.') {
				CommentsValue = document.feedback.comments.value;
			}
		}
	} else { CommentsValue="0"; }
	if (CommentsValue == "" ) {
		alert("Please enter your comments before submitting.");
		return false;
	}
}
function fcheck_required() {
	var CommentsValue = "";
	var EmailValue = document.feedback.answer_6.value;
	if(typeof document.feedback.comments!='undefined') {
		if(typeof document.feedback.comments.value!='undefined'){
			if (document.feedback.comments.value != 'Please enter your comments about this webpage here.') {
				CommentsValue = document.feedback.comments.value;
			}
		}
	} else { CommentsValue="0"; }
	if (CommentsValue == "" ) {
		alert("Please enter your comments before submitting.");
		return false;
	} else if (EmailValue == "") {
		alert("Please enter your email address.");
		return false;
	}
}
function textCounter(field,cntfield,maxlimit) {
	if (field.value.length > maxlimit) {
		field.value = field.value.substring(0, maxlimit);
    } else {
		cntfield.value = maxlimit - field.value.length;
    }
}
function clearTextArea() {
    if (document.feedback.cleared.value == '') {
        document.feedback.cleared.value = 1;
        document.feedback.comments.value = '';
    }
}

function showAllSavedVehicles() {
    $("#sv_sa").hide();
    $("#sv_sl").show();
    $(".sv:hidden").show();
}

function showLessSavedVehicles() {
    $("#sv_sl").hide();
    $("#sv_sa").show();
    $(".sv:gt(2)").hide();
}

function getCookie ( cookie_name ) {
    var results = document.cookie.match ( cookie_name + '=(.*?)(;|$)' );
    if (results) {
        return ( unescape ( results[1] ) );
    } else {
        return null;
    }
}

function setCookie (name, value, seconds) {
    var date = new Date();
    date.setTime(date.getTime() + (seconds*1000));
    var expires = "; expires=" + date.toGMTString();
    document.cookie = name+"="+value+expires+"; path=/";
}

function removeSavedVehicle(vehicle, vehicle_id) {
    var savedVehicles = getCookie("savedVehicles");
    var arr = savedVehicles.split("|");
    for (var i in arr) {
        if (vehicle == arr[i].replace(/\+/g," ")) {
            arr.splice(i,1);
        }
    }
    var newSavedVehicles = "";
    var seconds = '-1';
    if (arr.length > 0) {
        newSavedVehicles = arr.join('|');
        seconds = 31*60*60*24;
    }
    setCookie('savedVehicles', newSavedVehicles, seconds);
    $("#sv_id_"+vehicle_id).remove();
    $(".sv:nth-child(3):hidden").show();
    if ($(".sv").size() < 4) {
        $("#sv_sl:visible").hide();
        $("#sv_sa:visible").hide();
    }
    if ($(".sv").size() == 0) {
        $("#myGarage").hide();
    }
}
if (typeof($) != "undefined") {
    $(function() {
        if (typeof(document.searchkeyword) != "undefined") {
            document.searchkeyword.Ntt.focus();
        }
    });
}

function ManageTabPanelDisplay() {
	var idlist = new Array('tab1focus','tab2focus','tab3focus','tab4focus','tab1ready','tab2ready','tab3ready','tab4ready','content1','content2','content3','content4');
	if (arguments.length < 1) { return; }
	for (var i = 0; i < idlist.length; i++) {
		var block = false;
		for (var ii = 0; ii < arguments.length; ii++) {
			if (idlist[i] == arguments[ii]) {
				block = true;
				break;
			}
		}
		if (document.getElementById(idlist[i]) != null) {
			if (block) {
				document.getElementById(idlist[i]).style.display = "inline";

				// highlight tabs that is current selected
				var re = new RegExp("focus", "g");
				if (idlist[i].match(re)) { document.getElementById(idlist[i]).className = "active"; }
			}
			else { document.getElementById(idlist[i]).style.display = "none"; }
		}
	}
}

function showHoverBox(active) {
	var idlist = new Array('category-hover-box1','category-hover-box2','category-hover-box3','category-hover-box4','category-hover-box5','category-hover-box6','category-hover-box7','category-hover-box8');
	if (arguments.length < 1) { return; }

	for (var i = 0; i < idlist.length; i++) {
		var block = false;
		if (document.getElementById(idlist[i]) != null) {
			if (active == idlist[i]) { document.getElementById(idlist[i]).style.display = "inline"; }
			else { document.getElementById(idlist[i]).style.display = "none"; }
		}
	}
}


function SelectSavedVehicle() {
    var editsavedvehicles = document.editsavedvehicles;
    var index = 0;
    var ymm = "";

    for (var i = 0; i < editsavedvehicles.savedvehicle.length; i++) {
        if (editsavedvehicles.savedvehicle[i].checked) {
            ymm = editsavedvehicles.savedvehicle[i].value;
            index = i;
        }
    }

    if (index == 0) {
        return false;
    }
    else {
        for (var i = 0; i < JSON_obj.savedvehicles.length; i++) {
            if (JSON_obj.savedvehicles[i].id == ymm) {
                editsavedvehicles.year.value  = JSON_obj.savedvehicles[i].year;
                editsavedvehicles.make.value  = JSON_obj.savedvehicles[i].make_text;
                editsavedvehicles.model.value = JSON_obj.savedvehicles[i].model_text;

                break;
            }
        }

        return true;
    }
}


function SelectSavedVehicles() {
    var savedvehicles = document.savedvehicles;

    for (var i = 0; i < JSON_obj.savedvehicles.length; i++) {
        if (JSON_obj.savedvehicles[i].id == savedvehicles.sv_ymm.value) {
            savedvehicles.year.value  = JSON_obj.savedvehicles[i].year;
            savedvehicles.make.value  = JSON_obj.savedvehicles[i].make_text;
            savedvehicles.model.value = JSON_obj.savedvehicles[i].model_text;

            break;
        }
    }

    savedvehicles.submit();
}

function tryAnotherVehicle()
{
	  	document.getElementById("vehicle_fits").style.display = 'block';
	  	document.getElementById("part_fits").style.display = 'none';
	  	document.getElementById("part_not_fits").style.display = 'none';
}

// loops through all navigation tabs and execute mouseout and mouseout actions
function navHover()
{

	if(document.getElementById("nav"))
	{

		var obj = document.getElementById("nav");
		var ArrayLi = obj.getElementsByTagName('li');
		var nav_id;

		for (var i =0 ; i < ArrayLi.length; i++ )
		{
			if ( ArrayLi[i].id != "" )
			{
				nav_id = ArrayLi[i].id;
				if (nav_id.length > 0)
				{
					document.getElementById(nav_id).onmouseover = function ()
					{
						toggleDropDowns("off");
						this.className += ' hoverIn';
					};

					document.getElementById(nav_id).onmouseout = function ()
					{
						toggleDropDowns("on");
						this.className = this.className.replace(' hoverIn',"");
					};
				}
			}
		}
	}
}

// show/hide dropdowns
function toggleDropDowns(toggle) {
	var selNodes = document.getElementsByTagName('select');
	var max = selNodes.length;

	for (var i=0; i<max; i++) {
		var nodeObj = selNodes[i];

		if (nodeObj.id != 'search-dd') {
			if (toggle == "off") {
				nodeObj.style.visibility = 'hidden';
			} else {
				nodeObj.style.visibility = 'visible';
			}
		}
	}
}

//check if the value is numeric
function Is_Numeric(id) {
	var id_name = '#' + id;
	$(id_name).keyup( function() {
      var qty = document.getElementById(id).value;

      var ValidChars = "0123456789.";
   	  var IsNumber=true;
   	  var Char;

	 for (i = 0; i < qty.length && IsNumber == true; i++)
      {
	      Char = qty.charAt(i);
	      if (ValidChars.indexOf(Char) == -1)
          {
	      	   IsNumber = false;
	      	   break;
         }
      }
	 if(IsNumber == false) { document.getElementById(id).value = 1 ;}
	}
      );

}



//load navHover on  IE6 only
function menuTabCheck() {
	var ua = window.navigator.userAgent;
	var msie = ua.indexOf ( "MSIE " );
	if (msie > 0) {
		vernum = parseInt(ua.substring (msie+5, ua.indexOf (".", msie )));
		if (vernum < 7) {
			navHover();
		}
	}
}

// expand/collapse category and brandlisting in Other Results of results pages
if (typeof($) != "undefined") {
    $(document).ready(function() {
    	$('#toggle-cat_more').click( function() {
    		$('#category-more').toggle();
    		$('#toggle-cat_more').hide();
    		$('#toggle-cat_less').show();
    	});
    	$('#toggle-cat_less').click( function() {
    		$('#category-more').toggle();
    		$('#toggle-cat_more').show();
    		$('#toggle-cat_less').hide();
    	});
    });
}

// collapse/expand category, sub-categories, sibling cateogries, and refinements
$(document).ready(function()
{

  // hide all collapsed containers
  $(".collapsed .collapsed-content").hide();

  //toggle the componenet with class msg_body
  $(".link-group h3").click(function()
  {
    $(this).next(".collapsed-content").slideToggle();
    //$(this).next(".collapsed-content").toggle();

    // change css
    $(this).parent("div").toggleClass("collapsed");

  });
});

function viewContainerContents(viewContents, hideContents){
       $('#'+viewContents).show();
       $('#'+hideContents).hide();
}

function in_array(needle, haystack, strict) {
	var found = false, key, strict = !!strict;

	for(key in haystack) {
		if((strict && haystack[key] === needle) || (!strict && haystack[key] === needle)) {
			found = true;
			break;
		}
	}
	return found;
}

/**
Validates entries in a form
*/
function validate() {
	var username = $("#customer_username").val();

	if (IsEmpty(username)) {
		alert("Please enter all fields to continue");
		return false;
	}
	if ( !IsEmail ( username ) ) {
		alert("Must supply a valid Email Address");
		return false;
	}
	return true;
}

function emailValidate() {
	var email = $("#email").val();
	if ((IsEmpty(email)) || (email.toLowerCase() == 'enter email address')) {
		alert("Please enter your email address to continue.");
		return false;
	} else {
		if ( !IsEmail ( email ) ) {
			alert("Please supply a valid email address");
			return false;
		}
	}
	return true;
}

function subscribeValidate() {
	var semail = $("#semail").val();
	if ((IsEmpty(semail)) || (semail.toLowerCase() == 'enter your email address')) {
		alert("Please enter your email address to continue.");
		return false;
	} else {
		if ( !IsEmail(semail) ) {
			alert("Please supply a valid email address");
			return false;
		}
	}
	return true;
}

function IsEmpty(value) {
	value = jQuery.trim(value);
	if (value == "") return true;
	else return false;
}
function IsFloat(a) {
    a = jQuery.trim(a);
    if (parseFloat(a)) return true;
    else return false
}
function IsPhone(a) {
    var b = /^\d+([\d-])*$/;
    if (b.test(a)) return true;
    else return false
}
function IsEmail(email) {
	var regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
	if (regex.test(email)) return true;
	else return false;
}
function validateLogin() {
	var email 		= $("#email").val();
	var password 	= $("#password").val();

	if((IsEmpty(email)) && (IsEmpty(password))) {
		alert("Required fields are empty");
		return false;
	} else {
		if ((!IsEmpty(email))) {
			if ( !IsEmail ( email ) ) {
				alert("Please supply a valid email address");
				return false;
			}
		} else {
			alert("Email Address field is empty.");
			return false;
		}
		if ((IsEmpty(password))){
			alert("Password field is empty.");
			return false;
		}
	}
	return true;
}
/* Contact Auto Parts Warehouse */
function validateFormValues() {
	var name		= $("#name").val();
	var email 		= $("#email").val();
	var dept 		= $("#department").val();
	var rma 		= $("#rma").val();
	var msg 		= $("#message").val();

	if((IsEmpty(name)) && (IsEmpty(email)) && (IsEmpty(dept)) && (IsEmpty(msg))) {
		alert("Required fields are empty");
		return false;
	} else {
		if (IsEmpty(name)){
			alert("Name field is empty.");
			return false;
		}

		if (!IsEmpty(email)) {
			if ( !IsEmail ( email ) ) {
				alert("Please supply a valid email address");
				return false;
			}
		} else {
			alert("Email Address field is empty.");
			return false;
		}

		if (IsEmpty(dept)){
			alert("Please select a department.");
			return false;
		} else if ( dept == 'shipping'){
			if (IsEmpty(rma)){
				alert("Order and Part # field is empty.");
				return false;
			}
		}

		if (IsEmpty(msg)){
			alert("Message field is empty.");
			return false;
		}
	}
	return true;
}
/* track order */
function validateTrackOrder(){
	var orderID			= $("#order_id").val();
	var emailAddress	= $("#email_address").val();

	if ((IsEmpty(orderID)) && (IsEmpty(emailAddress))){
		alert("Required fields are empty.");
		return false;
	} else {
		if (IsEmpty(orderID)){
			alert("Order Number field is empty.");
			return false;
		}
		if(isNaN(orderID)){
			alert("Order Number field accepts numeric values only.");
			return false;
		}
		if (!alphanumeric(orderID))
		{
		    alert("Order Number field contains an invalid character.");
		}

		if ( !IsEmpty(emailAddress) ){
			if ( !IsEmail(emailAddress) ) {
				alert("Please supply a valid email address");
				return false;
			}
		} else {
			alert("Email Address field is empty.");
			return false;
		}

	}
	return true;
}

function alphanumeric(objval)
{
	var stringtocheck = objval;
	for(var j=0; j<stringtocheck.length; j++)
		{
		  var alphaa = stringtocheck.charAt(j);
		  var hh = alphaa.charCodeAt(0);
		  if((hh > 47 && hh<58) || (hh > 64 && hh<91) || (hh > 96 && hh<123))
		  {
		  }
		else	{

			 return false;
		  }
 		}
 return true;
}


/* price match */
function validatePriceMatchForm() {
	if ( IsEmpty($("#userName").val())) { alert("Missing Name!");	return false; }
	if ( IsEmpty($("#userEmail").val())) {
		alert("Missing E-Mail!");
		return false;
	} else {
		if ( !IsEmail($("#userEmail").val()) ) {
			alert("Not a valid E-Mail Address!");
			return false;
		}
	}
	if (!IsPhone($("#userPhoneNumber").val()) && !IsEmpty($("#userPhoneNumber").val())) {alert("Invalid Phone Number!");return false}
	if ( IsEmpty($("#partBrand").val())) { alert("Missing Brand Name!"); return false; }
	if ( IsEmpty($("#partNumber").val())) { alert("Missing Part Number!"); return false; }
	if ( IsEmpty($("#partDesc").val())) { alert("Missing Part Description!"); return false; }
	if ( IsEmpty($("#compPrice").val())) { alert("Missing Their Price!"); return false; }
	if (!IsFloat($("#compPrice").val())) {alert("Invalid Their Price!");return false}
	if ( IsEmpty($("#ourPrice").val())) { alert("Missing Our Price!"); return false; }
	if (!IsFloat($("#ourPrice").val())) {alert("Invalid Our Price!");return false}
	if ( IsEmpty($("#compShipping").val())) { alert("Missing Their Shipping Price!");	return false; }
	if (!IsFloat($("#compShipping").val()) && $("#compShipping").val() != 0) {alert("Invalid Their Shipping Charge!");return false}
	if (parseFloat($("#compPrice").val()) == parseFloat($("#ourPrice").val())) {alert("Their Price and Our Price are the same");return false; }
	if (parseFloat($("#compPrice").val()) > parseFloat($("#ourPrice").val())) {alert("Our Price is lower than Their Price");return false; }
	if ( IsEmpty($("#compURL").val())) { alert("Missing Url!"); return false; }
}

function encodeWithCase(str) {
	str = str.replace(/\ /g, "_");
	str = str.replace(/\//g, "-fs-");
	str = str.replace(/\&/g, "-and-");
	str = str.replace(/\./g, "-dot-");
	str = str.replace(/\"/g, "-qt-");
	str = str.replace(/\,/g, "-comma-");
	str = str.replace(/\(/g, "-openp-");
	str = str.replace(/\)/g, "-closep-");
	str = str.replace(/\+/g, "-plus-");

	str = str.replace(/^\s+|\s+$/g,"");
	return str;
}


function encode(str) {
	str = str.replace(/\ /g, "_");
	str = str.replace(/\//g, "-fs-");
	str = str.replace(/\&/g, "-and-");
	str = str.replace(/\./g, "-dot-");
	str = str.replace(/\"/g, "-qt-");
	str = str.replace(/\,/g, "-comma-");
	str = str.replace(/\(/g, "-openp-");
	str = str.replace(/\)/g, "-closep-");
	str = str.replace(/\+/g, "-plus-");

	str = str.toLowerCase();
	str = str.replace(/^\s+|\s+$/g,"");
	return str;
}

function encodeNrValue(str) {
	str = str.replace(/\&/g, "%26");
	str = str.replace(/\+/g, "%252B");
	return str;
}

function escapeQueryValue(str) {
	// $str = str_replace('\\', '\\\\', $str);
	str = str.replace(/\,/g, "\,");
	str = str.replace(/\(/g, "\(");
	str = str.replace(/\)/g, "\)");
	str = str.replace(/\:/g, "\:");
	str = str.replace(/\ /g, "\+");
	return str;
}

function decode(str) {
	str = str.replace(/\_/g, " ");
	str = str.replace(/\-fs\-/g, "/");
	str = str.replace(/\-and\-/g, "&");
	str = str.replace(/\-dot\-/g, ".");
	str = str.replace(/\-qt\-/g, "\"");
	str = str.replace(/\-comma\-/g, ",");
	str = str.replace(/\-openp\-/g, "(");
	str = str.replace(/\-closep\-/g, ")");
	str = str.replace(/\-plus\-/g, "+");
	return str;
}

function getQueryString( name ){
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );

	if( null == results ){
		return null;
	}
	else{
		return results[1];
	}
}

function collapse_items(obj){
	if(typeof 'undefined' != obj){
		for(var i in obj){
			document.getElementById(obj[i].id).style.display = obj[i].display;
		}
	}
}

function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return '';
}


function recalculate() {
	document.formbasket.Submit.value = 'Recalculate';
	document.formbasket.submit();
}
function savequote() {
	document.formbasket.Submit.value = 'Save Quote';
	document.formbasket.submit();
}
function remove(val) {
	document.formbasket.elements['remove[]'].value = val;
	document.formbasket.submit();
}
function more(popup_div, image, title, text) {

	var innertext = '';
	innertext += '<tr><td colspan=2>&nbsp;</td></tr>';
	innertext += '<tr><td colspan=2><div class="more_title">' + title + '</div></td><tr>';
	innertext += '<tr><td colspan=2>&nbsp;</td></tr>';
	innertext += '<tr><td colspan=2><div class="more_img"><img src="' + image + '"></div></td></tr>';
	innertext += '<tr><td colspan=2>&nbsp;</td></tr>';
	innertext += '<tr><td colspan=2><div class="more_txt">' + text + '</div></td></tr>';
	innertext += '<tr><td>&nbsp;</td></tr>';

	var div_width = 450;

	place_popup(popup_div, innertext, div_width);

}

function pop_cvv() {

	PositionX = 100;
	PositionY = 100;
	defaultWidth  = 450;
	defaultHeight = 300;
	var opt='resizable=yes,scrollbars=yes,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
	window.open('http://www.discounto2sensor.com/includes/secure/popup.php?type=cvv','',opt);

}

function core(popup_div) {

	var innertext = '';
	innertext += '<tr><td colspan=2 style="font-size:14px; padding:5px;">';
	innertext += '<br>To receive "core charge credit" The old part that you are replacing must';
	innertext += 'be returned to us. The old part must be returned in the original container';
	innertext += ' that your new product arrived in and must be in "re-usable" condition.'
	innertext += '<br><br>All core returns are handled within the standard return process requiring';
	innertext += ' a RETURN AUTHORIZATION NUMBER.<br><a target="_blank" href="http://http://www.discounto2sensor.com//account.php?section=rma">Click Here</a>';
	innertext += '<br><br>The core may only be returned for credit within the first 30 days of';
	innertext += ' receipt of your order. All handling and shipping fees are to be paid for';
	innertext += ' by the customer. Once your core has been verified to meet core standards,';
	innertext += ' credit will be issued against the original purchased core only. This may';
	innertext += ' take up to 3-4 weeks.';
	innertext += '</td></tr>';
	var div_width = 450;

	place_popup(popup_div, innertext, div_width);

}

function quote(popup_div) {

	var innertext = '';
	innertext += '<tr><td colspan=2 style="font-size:14px; padding:5px;">';
	innertext += '<br>The price quoted to you on this page can be saved for future reference.';
	innertext += ' If you would like to save this quote please <a href="javascript:savequote()">click here</a> and follow the instructions.';
	innertext += '<br><br>To retrieve a saved quote, please <a href="http://www.discounto2sensor.com/basket.php?quote=retrieve">click here</a> and enter your saved quote number.';
	innertext += '</td></tr>';
	var div_width = 450;

	place_popup(popup_div, innertext, div_width);

}

function cvv(popup_div) {

	var innertext = '';
	innertext += '<tr><td colspan=2 style="padding:10px; font-size:14px;"><p>This is an extra security measure to ensure that you have access or physical possession of the credit card itself in order to use the CVV code. For details on where to find your CVV code, please check below.</p></td></tr>';
	innertext += '<tr><td><img src="http://www.discounto2sensor.com/checkout.php?image=cvv_visa.jpg&type=pt_layout" border="0"></td><td valign=top><b>VISA</b><br>A three digit non-embossed number on the back of the card printed within the signature panel after the account number.</td></tr>';
	innertext += '<tr><td><img src="http://www.discounto2sensor.com/checkout.php?image=cvv_mastercard.jpg&type=pt_layout" border="0"></td><td valign=top><b>Master Card</b><br>A three digit non-embossed number on the back of the card printed within the signature panel after the account number.</td></tr>';
	innertext += '<tr><td><img src="http://www.discounto2sensor.com/checkout.php?image=cvv_amex.jpg&type=pt_layout" border="0"></td><td valign=top><b>American Express</b><br>A four digit non-embossed number on the face of the card.</td></tr>';
	innertext += '<tr><td><img src="http://www.discounto2sensor.com/checkout.php?image=cvv_discover.jpg&type=pt_layout" border="0"></td><td valign=top><b>Discover</b><br>A three digit non-embossed number on the back of the card printed within the signature panel after the account number.</td></tr>';
	innertext += '<tr><td>&nbsp;</td></tr>';
	var div_width = 450;

	place_popup(popup_div, innertext, div_width);

}

function place_popup(popup_div, innertext, div_width) {

	var popuptext = '';
	//popup header
	popuptext += '<div style="font-size:1px;">&nbsp;</div><div id="more_div'+popup_div+'" style="position:absolute; width:'+div_width+'px;">';
	popuptext += '<iframe id="iframe'+popup_div+'" style="top:0; left:0; position:absolute; height:100%; width:100%; font-size:1px;" src="http://www.discounto2sensor.com/checkout.php?html=blank.html&type=pt_layout" frameborder=0 scrolling=no marginwidth=0 marginheight=0></iframe>';
	popuptext += '<div id="div'+popup_div+'" style="top:0; left:0; position:absolute; width:'+div_width+'px; height:100% border:2px solid black;" class="more_div">';
	popuptext += '<table width=100% height=100% align=center cellpadding=0 cellspacing=0>';
	popuptext += '<tr><td height=25><img src="http://www.discounto2sensor.com/basket.php?image=logo.jpg&type=pt_layout"></td><td valign="top" align="right"><a href="javascript:remove_popup(\'' + popup_div + '\')"><img src="http://www.discounto2sensor.com/basket.php?image=close.jpg&type=pt_layout" border=0></a></td></tr>';
	popuptext += '<tr><td colspan=2><div class="more_hr">&nbsp;</div></td></tr>';
	//apply body to popup
	popuptext += innertext;
	//popup footer
	popuptext += '<tr><td colspan=2 align="center" valign=bottom><a href="javascript:remove_popup(\'' + popup_div + '\')"><img src="http://www.discounto2sensor.com/basket.php?image=closew.jpg&type=pt_layout" border=0></a>';
	popuptext += '<tr><td height=10>&nbsp;</td></tr>';
	popuptext += '</table><br style="clear:both"></div>';
	popuptext += '</div>';

	//get the id's and save them to a variable
	var more_div_anch = 'more_div'+popup_div;
	var iframe_div_anch = 'iframe'+popup_div;
	var div_div_anch = 'div'+popup_div;

	//get the anchor_div and append the innerhtml
	var anchor_div = document.getElementById(popup_div);
	anchor_div.innerHTML = popuptext;

	//get the height of the inside div and resize the iframe to that height
	//iframe is needed to block out form selects
	var more_div 		= document.getElementById(more_div_anch);
	var needheight = document.getElementById(div_div_anch);
	var setheight = document.getElementById(iframe_div_anch);
	setheight.style.height = needheight.clientHeight + 4;

	//make the div draggable
	Drag.init(more_div);

}

function remove_popup(div) {
	var anchor_div = document.getElementById(div);
	anchor_div.innerHTML = '<div style="font-size:1px;">&nbsp;</div>';
}

function sameAsBilling() {
 document.forminfo1.delivery_name.value               = document.forminfo1.customers_first_name.value + " " + document.forminfo1.customers_last_name.value;
 document.forminfo1.delivery_street_address.value     = document.forminfo1.customers_street_address.value;
 document.forminfo1.delivery_suburb_address.value     = document.forminfo1.customers_suburb_address.value;
 document.forminfo1.delivery_city.value               = document.forminfo1.customers_city.value;
 document.forminfo1.delivery_state.value              = document.forminfo1.customers_state.value;
 document.forminfo1.delivery_postcode.value           = document.forminfo1.customers_postcode.value;
 document.forminfo1.delivery_country.selectedIndex    = document.forminfo1.customers_country.selectedIndex;
}

function search_submit(){
	var keyword = document.getElementById("search_form_text");

	if(keyword.value=='Enter Keyword/SKU' || keyword.value.length==0){
		alert("Keyword is blank, please enter a keyword.");
		return false;
	}
}

function getCompare(f) {
	var R = '';
	var cnt = 0;
	for(var n=0; n<50; n++) {

		var e = document.getElementById("comp"+n);
		if(e != null) {
			if(e.checked) {
				R += e.value + ' ';
				cnt++;
			}
		}
	}

	if(cnt < 2) {
		alert("Please Select at least (2) two products for comparison");
		return false;
	}

	if(R.length > 0) {
		f.R.value = R;
		return true;
	} else {
		return false;
	}
}

function validateChecks(f) {

	var R = '';
	var chkCnt = 0;
	for(var n=0; n<50; n++) {

		var e = document.getElementById("comp"+n);
		if(e != null) {
			if(e.checked) {
				chkCnt++;
			}
		}

		if(chkCnt > 4) {
			alert("You may select up to (4) four products to compare");
			f.checked = false;
			break;
		}
	}
}

function passRCnt(brand, part, sku){
	document.getElementById("ymm_overlay_brand").value = brand;
	document.getElementById("ymm_overlay_part").value = part;
	document.getElementById("ymm_overlay_sku").value = sku;
}


/**
* Checkout Specific 
*/

function update(qty_id) {

	if(document.getElementById(qty_id).value == 0)
	{
        var order_item_id = qty_id.substr(3); /*remove 'qty' from qty_id (e.g. qty123) */
		remove(order_item_id);
	}
	else
	{
		document.formbasket.Submit.value = 'Update';
		document.formbasket.submit();

	}
}

function remove(val) {
    document.formbasket.Submit.value = 'Remove';
	document.formbasket.elements['remove[]'].value = val;
	document.formbasket.submit();
}

function pop_more(image, title, text, popWidth, popHeight) {
    if (!popWidth)
    {
        var popWidth  = 560;
        
    } 
    if (!popHeight) 
    {
        var popHeight = 570;
    }
	PositionX = 100;
	PositionY = 100;
	defaultWidth  = popWidth ;
	defaultHeight = popHeight;
	
	var opt='resizable=yes,scrollbars=yes,innerHeight=600,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
	window.open('/popup/more/image/'+image+'/title/'+title+'/text/'+text,'',opt);
    
}

function IsValidateString(objval,type)
{
    var stringtocheck = objval;
    if (!type)
    {
        var type = 'name'; // address | name
    }
    
    
    if (type == 'name')
    {
        var allowedchars = ". ";
    } else
    {
        var allowedchars = ".,# ";
    }


    for(var j=0; j<stringtocheck.length; j++)
    {
        var charval = stringtocheck.charAt(j);
        var hh = charval.charCodeAt(0);
        if (((hh > 47 && hh<58) || (hh > 64 && hh<91) || (hh > 96 && hh<123)) || (allowedchars.indexOf(charval) > 0))
        {
            
        }
        else	{      
            return false;
        }
    }
    
    return true;
}

