/*jsl:option explicit*/

/*
2008-2009 Brett Knights. All rights reserved. This material may not be reproduced,
displayed, modified or distributed without the express prior written
permission of the copyright holder.
*/

var KOTN = function(){

	function lPad(num){
		if(num < 10) return "0" + num.toString();
		return num.toString();
	}

	return {

	 setValueTitle: function(target){
			if(!target.value ) target.value = target.getAttribute("title");
		},

	setMyFrameHeight: function(){ // call whenever more nodes are added to this page
		if(parent && parent.resizeIFrame){
			parent.resizeIFrame(jQuery('iframe.formFrame', parent.document ? parent.document : parent.contentDocument).get(0));
		}
	},

	setReturnURL:	function (url){
		var target = window.parent ? window.parent : window;
		var location = target.location.href;
		if (url && url != "") { location = url; } 
		this.setCookie('intendedLocation', location);
	},

	checkLoggedIn: function(isTrue, isFalse){ // callbacks for discovered state

		if (!(this.custId && parseInt(this.custId, 10) > 0)){ // must be set up in client header
			isFalse(true);
			return;
		}
		try{
			var origHandler = window.onerror;
			var alreadyCheckedIt = false;
			function checkedIt(isLogged){
				try{
					if (!alreadyCheckedIt) {
						alreadyCheckedIt = true;
						if(isLogged) isTrue();
						else isFalse();
					}
				}catch(e){alert(e);}
				window.onerror = origHandler;
			}
			window.onerror = function(msg, url, line){checkedIt(false);  return true;};
			jQuery.getJSON("https://checkout.netsuite.com/app/site/hosting/scriptlet.nl?script=4&deploy=1&compid=1048954&h=e8051767ce6de18dcecd&jsoncallback=?", function(ui){
				try{
					if (ui.userAccountId && typeof ui.userAccountId != "undefined"){
						if(parseInt(ui.userAccountId, 10) > 0){
								KOTN.isLogged = true;
								KOTN.custId = ui.userAccountId;
								checkedIt(true);
								return;
						}
					}
				}catch(e){;}
				checkedIt(false);
			});
			if(!IsJSONWorking) { //this variable is set outside this script
				checkedIt(false); //DTH Feb27-2010 Added to cause login if above JSON call returns non-JSON object
			}
			//DTH: this is not an ideal solution as ideally we would be able to react when the json call above returns a non-json object, but at the moment it just fails silently.
			// This is likely due to the fact that the request is considered remote, as it has to communicate by creating a <script> tag and executing the jsoncallback function inside the tag
			// When the function is not inside the script tag, nothing is done and it dies silently.  There should be a way to fix this, but that is future work (and perhaps a 'bug' in jquery).
		}catch(e){
			checkedIt(false);
		}
	},

/*jsl:ignore*/
	printf: function(sentence, reps){
		var calls = 0;
		var parts = sentence.split("%x");
		var a ="";
		for(var i = 0; i< parts.length; i++) a+= parts[i] + ((calls < reps.length) ? reps[calls++] : "" );
		return a;
	},

	mapPrintf: function(sentence, map){
		var parts = xSplit(sentence, /(%x\.|\.x%)/);
		if(parts.length == 1) return sentence; //but why call?
		var v = "";
		for(var i = 0; i< parts.length; i++){
			if(parts[i] != "%x.") v += parts[i];
			else if (parts[i] == "%x."){
				var key = parts[++i];
				if(map[key] === undefined) throw Error (key + " is undefined in sentence:\n" + sentence);
				v += map[key];
				if(parts[++i] != ".x%") throw Error("imbalanced x%..%x delimiters");
			}
		}
		return v;
	},

/*jsl:end*/

	monthAbbrevs: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],

	formatDate: function(date){
			 // returns dd-M-yy formatted date
			 if(!date) return "";
			 return date.getDate() + "-" + this.monthAbbrevs[date.getMonth()] + "-" + date.getFullYear();

	},

	formatInputDate: function(date){
		if(!date) return "";
		return lPad(date.getUTCMonth() + 1) +"/" + lPad(date.getUTCDate()) + "/" + date.getUTCFullYear();
	},

	showMessage:function(msg, msgId, data){
		if(document.getElementById(msgId)) jQuery("#" + msgId).show(100);
		else if(document.getElementById("qv-messageElem")) {
					jQuery("#qv-messageElem > div:not(:first)").remove();
					jQuery("#qv-messageElem").append("<div style='white-space:pre;'>" + (data ? this.printf(msg, data) : msg) + "</div>").show();
		} else alert (data ? this.printf(msg, data) : msg);
	},

	showError: function(msg,msgId, data){
		if(document.getElementById(msgId)) jQuery("#" + msgId).show(100);
		else if(document.getElementById("qv-messageElem")) {
					jQuery("#qv-messageElem > div:not(:first)").remove();
					jQuery("#qv-messageElem").append("<div style='color:red;white-space:pre-wrap;'>" + (data ? this.printf(msg, data) : msg) + "</div>").show(100);
		} else alert(data ? this.printf(msg, data) : msg);
	},

	getQueryParamList: function(targetWin){
		if(!targetWin) targetWin = window;
		if(!targetWin.queryParams){
			targetWin.queryParams = {};
			if (targetWin.location.search){
				var qp = {};
				var pairs = targetWin.location.search.substring(1).split("&");
				for(var i = 0; i< pairs.length; i++){
					addParam(qp, pairs[i].split("="));
				}
				targetWin.queryParams = qp;
			}
		}
		return targetWin.queryParams;

		function addParam(h, nvPair){
			if(nvPair.length !== 2) return;
			var storedValue = h[nvPair[0]];
			if(!storedValue) h[nvPair[0]] = unescape(nvPair[1]);
			else if(storedValue.constructor == Array) storedValue.push(unescape(nvPair[1]));
			else h[nvPair[0]] = [storedValue, unescape(nvPair[1])];
		}
	},

	getQueryParam: function(name, targetWin){
		var pList = this.getQueryParamList(targetWin);
		var pValue = pList[name];
		if(!pValue) return "";
		if(pValue.constructor == Array) return pValue[0];
		return pValue;
	},

	getQueryParamValues: function(name, targetWin){
				var pList = this.getQueryParamList(targetWin);
				var pValue = pList[name];
				if(!pValue) return [];
				if(pValue.constructor == Array) return pValue;
				return [pValue];
	},

	getCookie: function (name){
		var targetPatt = new RegExp(name + '=([^;]+);?', "i");
		var val = targetPatt.exec(document.cookie);
		if(val && val.length == 2){
			return unescape(val[1]);
		}
		return "";
	},

	setCookie: function (name, value, days, expires){
		var expDate = (expires ? expires.toGMTString()  : ( days ? new Date(new Date().getTime() + days * 86400000).toGMTString() : null ));
		if(expDate){
			document.cookie = name + '=' + escape(value) + '; path=/;expires=' + expDate + ";";
		} else 	document.cookie = name + '=' + escape(value) + '; path=/';
	},

	clearCookie: function (name){
		document.cookie = name + '=; path=/;expires=Thu, 01-Jan-1970 00:00:01 GMT';
	},

	setElemText: function(elem, value){ // only works for structures with a single nested text node

		elem.normalize(); // delete ignorable white space nodes
		var target = getTextNode(elem);
		if(target) {
			target.parentNode.replaceChild(document.createTextNode(value), target);
			return;
		}

		if(elem.getAttribute('value')) {
			elem.setAttribute('value', value);
		}

		function getTextNode(n){
			if(n.nodeType != 1) return null;
			var c = n.firstChild;
			while(c)	{
				if(c.nodeType == 3) return c;
				if(c.nodeType == 1){
					var x = getTextNode(c);
					if(x) return x;
				}
				c = c.nextSibling;
			}
			return null;
		}

	}
};
}();


jQuery(document).ready(function(){
	var $ = jQuery;
	try{
		window.status  = "in before";

		$("div.messageCloser *").bind("click", KOTN.hideParent);
		$("#menu a, #footer a").click(function(){KOTN.clearCookie('intendedLocation'); return true;});
		if((/[&?]login=T\b/).test(document.location.search) // adjust login screen
			&& !((/[&?]sc=22\b/).test(document.location.search)) // do not apply to alerts page
			&& !((/[&?]sc=46\b/).test(document.location.search)) ){ // do not apply to RoD signup page
			
			$("#retemail").before($('#retemail_fs_lbl a').text("Email:").parent());
			$("#retpwd").before($('#retpwd_fs_lbl a').text('Password:').parent());
			$("#forgotpwdlink").after(document.getElementById('registerlinklink'));
			if(!(/[&?]newcust=T\b/).test(document.location.search)) $("#submitter").val("Sign In");
			$("#maincontents").addClass("onregpath");
		}
	}catch(e){
		window.status = e.message;
	}

	KOTN.checkLoggedIn(function(){
		$("div,span,li,ul").filter(".qv-loggedIn").show(100);
		$("div,span,li,ul").filter(".qv-notLoggedIn").hide(100);
	}, function(){
		$("div,span,li,ul").filter(".qv-loggedIn").hide(100);
		$("div,span,li,ul").filter(".qv-notLoggedIn").show(100);
	});
});

KOTN.hideParent = function(event){ // button in a div in a div
	event.stopPropagation();
	jQuery(event.target.parentNode.parentNode).hide();
};

function resizeIFrame(target){
	var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1];
	var FFextraHeight=parseFloat(getFFVersion)>=0.1? 32 : 0; //extra height in px to add to iframe in FireFox 1.0+ browsers

	function getMinHeight(ht){
		if(!jQuery.browser.safari) return ht;
		var minHeight = parseInt(target.style.height, 10);
		if(!isFinite(minHeight) || !(minHeight > 0)) return ht;

		return ht < (minHeight + 0) ? minHeight : ht;
	}

	if (target && !jQuery.browser.opera){
			target.style.display="block";

			var innerDoc = (target.contentDocument) ? target.contentDocument : target.contentWindow.document;
			if (innerDoc.body.offsetHeight){ //ns6 syntax
				target.height = getMinHeight(innerDoc.body.offsetHeight + FFextraHeight);
			}else if (target.Document && target.Document.body.scrollHeight){ //ie5+ syntax
				target.height = getMinHeight(target.Document.body.scrollHeight);
			}else {
				try{
					var ht = parseInt(innerDoc.defaultView.getComputedStyle(innerDoc.body,"").getPropertyValue("height"), 10);
					if(isFinite(ht)) target.height = getMinHeight(ht);
				}catch(e){}
			}

			//safari bug
			if(jQuery.browser.safari){
				target.style.overflow = "scroll";
			}
	}
}





/* ************************************** */
/* ********* Below code by DTH ********** */
/* ************************************** */

// Custom QV javascript functions DaveH

//var MYACCOUNT_REDIRECT_COOKIE_NAME = "MyAccountRedirect";
//var MYACCOUNT_REDIRECT_COOKIE_OPTIONS = { path: '/' };

var CART_COOKIE_NAME = "CartContents";
var CURRENT_URL_COOKIE_NAME = "CurrentURL";
var PREVIOUS_URL_COOKIE_NAME = "PreviousURL";

var previousURL = "";
var previousPreviousURL = "";

$("document").ready(function() {
    setCartContentsCookie();
	setCurrentURLCookie();
	setBackButton();
});


//tell the back button on the page (if there is one) where to send the user
function setBackButton() {
	var $ = jQuery;
	//if cookie was not set properly, use browser's back button
	$("#backbutton").click( function(e) { 
			if (previousURL != "" && previousURL != null && previousURL != window.location.href) {
				location.href = previousURL;
			} else if (previousPreviousURL != "" && previousPreviousURL != null && previousPreviousURL != window.location.href) {
				location.href = previousPreviousURL;
			} else {
				//if all else fails, "click" browsers back button
				history.go(-1);
			}
		});
}


//store current URL to create a back button on the next page
function setCurrentURLCookie() {
    previousURL = ( KOTN.getCookie(CURRENT_URL_COOKIE_NAME) ) ? KOTN.getCookie(CURRENT_URL_COOKIE_NAME) : "";
    previousPreviousURL = ( KOTN.getCookie(PREVIOUS_URL_COOKIE_NAME) ) ? KOTN.getCookie(PREVIOUS_URL_COOKIE_NAME) : "";
	//if the current and previous are the same, a refresh was done, do not update cookie
	if (previousURL != window.location.href) {
		KOTN.setCookie(CURRENT_URL_COOKIE_NAME, window.location.href);
		KOTN.setCookie(PREVIOUS_URL_COOKIE_NAME, previousURL);
	}
}

//Set cookie to contain all items in the cart (should be called only from cart page)
function setCartContentsCookie() {
	var $ = jQuery;
    //check if we are on cart page
    if ($('#carttable').length) {
        var filterCartItemIdRegExp = /.*item(\d+)set.*/;
        var cookieEntries = new Array();
        $('#carttable input').each(function() {
            var inputName = this.name;
            if (filterCartItemIdRegExp.test(inputName)) {
                inputName = inputName.replace(filterCartItemIdRegExp, "$1");
                cookieEntries.push(inputName);
            }
        });
        KOTN.setCookie(CART_COOKIE_NAME, cookieEntries.join(","), 365);
    }
}

//Reset cookie to ensure there is no duplicates with other Path options
function resetCartContentsCookie() {
    var currentCookie = KOTN.getCookie(CART_COOKIE_NAME);
    KOTN.clearCookie(CART_COOKIE_NAME);
    if (currentCookie) KOTN.clearCookie(CART_COOKIE_NAME, currentCookie, 365);
}

function addCheckmarksToCartContents() {
	var $ = jQuery;
    try {
        var currentCookie = KOTN.getCookie(CART_COOKIE_NAME);

        //Reset all checkmarks to be hidden to start with
        $('#right_container .job_container_box .heading .incart_checkbox img').hide();

        if (currentCookie) {
            var cookieEntries = currentCookie.split(",");

			//Check if the number of items in cart agrees with number of items in cookie
			//if not, do not display checkmarks
			var itemsInCart = $("#header_cart_count").text().match(/^\((\d) /);

			if (itemsInCart[1] == cookieEntries.length) {
				for (i = 0; i < cookieEntries.length; i++) {
					$('#right_container .job_container_box .heading .incart_checkbox img#checkbox_item' + cookieEntries[i]).show();
				}
			}
        }
    } catch (e) {
        //nothing here
    }
}

function addCommasToNumber(inputNum) {
    try {
        //remove everything except numbers and decimal places
        var outputNum = inputNum.toString().replace(/[^0-9\.]/g, "");

        //split at decimal place
        //note: if there is more than 1 decimal place, anything after the 2nd decimal will be discarded
        var splitDecimal = outputNum.split(".");
        var preDecimal = splitDecimal[0];
        var postDecimal = "";
        if (splitDecimal[1]) postDecimal = "." + splitDecimal[1];

        //add commas separating the thousands
        var testThousands = /(\d+)(\d{3})/;
        var preventInfiniteLoop = 100;
        while (testThousands.test(preDecimal) && preventInfiniteLoop > 0) {
            preDecimal = preDecimal.replace(testThousands, "$1" + "," + "$2");
            preventInfiniteLoop -= 1;
        }

        return (preDecimal + postDecimal);
    } catch (e) {
        //nothing here
    }
}

//Customize the checkout login/returning users page
//Based on KOTN code in QVPortalFunctions, same copyright applies
jQuery("document").ready(function() {
	var $ = jQuery;
	try {
		if((/[&?]sc=4\b/).test(document.location.search) && $("form#login").length != 0){ // adjust login screen
			$("#retemail").before($('#retemail_fs_lbl a').text("Email:").parent());
			$("#retpwd").before($('#retpwd_fs_lbl a').text('Password:').parent());
			// $("#forgotpwdlink").after(document.getElementById('registerlinklink'));
			$("#register").val("Register");
			$("#submitter").val("Sign In");
			$("#maincontents").addClass("onregpath");
			
			//move the column (<td>) containing the new user block to
			//after the column containing the returning users block,
			//so they will be in the same row (<tr>)
			$("#submitter").closest("td").parent().closest("td").parent().closest("td").after(
				$("#register").closest("td").parent().closest("td").parent().closest("td") );
			 
			//position the Register button (requires undoing of the negative left margine in css)
			//$("#register").closest("td").css("position","relative");
			$("#register").css("margin-left","0");
			$("#register").css("margin-right","6em");
			$("#register").css("position","static");
			$("#register").closest("table").css("float","right");

			//apply the same positioning to the Sign In button for consistency
			$("#submitter").css("margin-left","0");
			$("#submitter").css("margin-right","6em");
			$("#submitter").css("position","static");
			$("#submitter").closest("table").css("float","right");
			
			//add some space to the left margin of the page
			$("#submitter").closest("table").parent().closest("table").parent().closest("table").css("margin-left", "6em");

			//set size of new user column to be same as returning users
			//this may need tweaking
			$("#submitter").closest("table").parent().closest("table").css("width", "35em");
			$("#register").closest("table").parent().closest("table").css("width", "35em");
			$("#register").closest("table").parent().closest("table").closest("td").css("vertical-align", "top");
			//$("#submitter").closest("table").parent().closest("table").css("width") );
				
			//vertical align New Users column
			
			//increase font size of "New to our service?" text
			$("#register").closest("tr").parent().closest("tr").siblings().find("td.smalltext").css("font-size","11pt");
		}
	} catch(e) { window.status = e.message; }
	
	
	//Remove Continue Shopping button from reset password email screen
	try {
		if((/[&?]forgotPasswd=T\b/).test(document.location.search) && $("input#cancel[value='Continue Shopping']").length != 0){
			$("input#cancel[value='Continue Shopping']").hide();
		}
	} catch(e) { window.status = e.message; }

	try {
		//Remove Finished button from my profile
		if((/\/custprofile\.nl\b/).test(document.location.href)) {
			$("input#submitter[value='Finished']").hide();
		}
		//Remove PO # field from review and submit page in checkout
		if((/[&?]sc=4\b/).test(document.location.search) &&
			$("tr > td > span#otherrefnum_fs_lbl > a").text() == "PO #"){ 
				$("tr > td > span#otherrefnum_fs_lbl").parent("td").parent("tr").hide();
		}

/* no longer necessary as flow player does not exist
		//Remove flow player from login pages
		if((/[&?]login=T\b/).test(document.location.search)){ // adjust login screen
			$("#lpplayer").remove();
			$("#new_left_td").hide();
			$("div.content").css("padding-left","200px");
			$("div.content").css("position","relative");
		}
*/		
		//Redirect user to My Account if ever sent to unused page card.nl (e.g. after password)
		if((/\/app\/center\/card.nl\b/).test(document.location.href)) {
			location.href = "http://www.qualifiedvendor.com/s.nl/sc.34/.f";
		}

		//Change page user is sent to after password reset (after forgot password email)
		if((/[&?]passwdret=T\b/).test(document.location.search) &&
		    (/[&?]passretget=T\b/).test(document.location.search)) {
			var newSC = $("form#changepassword > input[name='sc']").val().replace(/4/,"1");
			$("form#changepassword > input[name='sc']").val(newSC);
		}
		
		//TODO: fix style of cancel button in change password (band-aid for now)
		//if((/[&?]passwdret=T\b/).test(document.location.search)) {
		//	$("form#changepassword input#cancel").css("width","60px !!important");
		//}
		
		//Redirect user off locations which should not be viewed directly
		if (location.pathname.toString() == "/mfg-rfqs" && location.search.indexOf("search") == -1) {
			location.pathname = "/mfg-rfqs/all-open-rfqs";
		}
		if (location.pathname.toString() == "/mfg-quotes" && location.search.indexOf("search") == -1) {
			location.pathname = "/mfg-quotes/aluminum-extrusions";
		}
	} catch(e) { window.status = e.message; }
	
});
