var isMac = navigator.userAgent.indexOf('Mac') > 0;
var isSafari = navigator.userAgent.indexOf('Safari') > 0;
var _GET = new Array();
var u = document.URL.split("?");
var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
var days = new Array(31,28,31,30,31,30,31,31,30,31,30,31);

if (u.length > 1) {
    var t = u[1].split("&");
    var objCtr;
    for(objCtr=0;objCtr<t.length;objCtr++) {
        var vars = t[objCtr].split("=");
        var key = eval('"'+ vars[0] +'"');
        var value = vars[1];
        _GET[key] = value;
    }
    
}


String.prototype.repeat = function (myNum){
    var str, i;
    this.str = this;
    for(i=1;i<myNum;i++){
        this.str = this.str + this;
    }
    return this.str;
}

String.prototype.getVar = function(key){
	var i;
	var varArray = this.split('&');
	for(i in varArray){
		var k = varArray[i].split('=')[0];
		var v = varArray[i].split('=')[1];
		if(k == key){
			return v;
		}
	}
	return false;
}

String.prototype.repVar = function(oVar,nVar){
	var i;
	var varArray = this.split('&');
	for(i in varArray){
		var k = varArray[i].split('=')[0];
		var v = varArray[i].split('=')[1];
		if(k == oVar){
			varArray[i] = k+'='+nVar;
		}
	}

	return varArray.join('&');
}

Number.prototype.formatNum = function() {
		

}

String.prototype.WordUp = function() {
	var regx = /\s+/;
	var i
	var str
	
	this.str = this.charAt(0).toUpperCase(); 
	for (i=1;i<this.length;i++) {
		 if (this.charAt(i-1).match(regx)) {
		 	this.str += this.charAt(i).toUpperCase()
		 } else {
		 	this.str += this.charAt(i);
		 }
	}
	return this.str;
}

String.prototype.toWordCase = function() {
	//changes a string formatted as foo_bar to Foo Bar, in other words -- Capitalize the first letter, 
	//every word after an underscore, and get rid of the underscore.
	var uscore = /[_]+/g;
	var i
	var str
	
	this.str = this.charAt(0).toUpperCase(); 
	for (i=1;i<this.length;i++) {
		 if (this.charAt(i-1).match(uscore)) {
		 	this.str += this.charAt(i).toUpperCase()
		 } else {
		 	this.str += this.charAt(i);
		 }
	}
	return(this.str.replace(uscore, ' '));
}

String.prototype.sentenceCase = function() {
	var str;
	this.str = this.charAt(0).toUpperCase();
	this.str += this.substring(1, this.length)
	return this.str
}

/*
Object.prototype.createOptions =function(args){
	if(args.length < 1) return;
//	alert(this);
	//var myOpts = new Array();
	for(var i = 0; i < args.length; i++){
		var opt = (args[i] != '') ? args[i].split('\t'):'';
		if (opt) {
			this.options[i] = new Option(opt[1],opt[0]);
		}
	}
	//return myOpts;
}
*/

function capitalize_form_data(formObj){
	var i;
	if (formObj.length > 0) {
		for (i = 0;i < formObj.length-1;i++){
			if(formObj[i].type == 'text' && formObj[i].value != '') {
				formObj[i].value = formObj[i].value.WordUp();
			}
			
		}
	}
	
}

function prefill_shipaddr(){
	copy_input_value('billing_address_1','shipping_address_1');
	copy_input_value('billing_address_2','shipping_address_2');
	copy_input_value('billing_city','shipping_city');	
	init_dd(document.forms[1].shipping_state, document.forms[1].billing_state.value);
	copy_input_value('billing_zip','shipping_zip')
}

function clear_shipaddr(){
	clear_input_value('shipping_address_1');
	clear_input_value('shipping_address_2');
	clear_input_value('shipping_city');
	clear_input_value('shipping_state');
	clear_input_value('shipping_zip');


}

function clear_input_value(v){
	document.getElementById(v).value='';
}

function copy_input_value(v1,v2){
	if((!document.getElementById(v1)) && (!document.getElementById(v2))) return;
	document.getElementById(v2).value = document.getElementById(v1).value;
}

function validate(formObj) {

	var reqlist = '';
	var i;
	
	for (i = 0;i < formObj.length-1;i++) {
	
		if ((formObj[i].className == 'required') && (formObj[i].value == '')) {
			
			if(formObj[i].id) {
				reqlist += formObj[i].id.toWordCase() + ', ';
			} else {
				reqlist += formObj[i].name.toWordCase() + ', ';
			}

		}
	}	    
    
	if (reqlist.length > 0) {
	    //replace any [] with nothing if necc.
    	reqlist = reqlist.replace(/\[\]/g, '');
    		
		alert('The following required field(s) were left blank:\n' + reqlist.substring(0, reqlist.length-2) +'\nPlease complete the form before continuing.')
		return false;

	} else {
	
		return true;
	}
}

function validate_email(v){
	var ex = (/^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/);

    return (ex.test(v));
}

function validate_sub(f){

	var valid = false;
	var em = f.email.value; 
	//alert(validate_email(em));
	//return false;
	if(em !='' && validate_email(em)){
		return true;
	}
	document.getElementById('suberr').innerHTML = 'valid address required';
	return valid;
}

function validate_radio(){
	if (arguments.length < 1) return false;
	if (arguments.length < 2) var msg = 'A required value was not chosen.';
			
	var myradio = arguments[0];
	var msg = arguments[1];
		
	if(myradio.checked) return true;
		for (i=0;i < myradio.length;i++) {
			if (myradio[i].checked) {
				return true;
			} else {
				continue;
			}
                
		}

		alert(msg);
		return false;
}

function numToCurr(num) {

	//formats a number (as string) to currency (a float with 2 point precision)
	
	num = Math.round(num * 100) / 100 + .00001;
	num = num.toString();
	num = num = num.split(".")[0] + "." + num.split(".")[1].substring(0,2);
	return num;

}

function numToFloatFour(num) {

	num = Math.round(num * 10000) / 10000 + .0000001;
	num = num.toString();
	num = num = num.split(".")[0] + "." + num.split(".")[1].substring(0,5);
	return num;

}

function validate_form(formobj){

    var ex = (/^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/);
    var f = formobj
    var valid = true
    var msg = "There were problems with your submission.\n"
    
    if (!ex.test(f.email_address.value)) {
        valid = false;
        msg += "You have entered an invalid e-mail address.\n"
    }
    
	if(f.email_address.value != f.email_address2.value){
		
		valid = false;
        msg += "Email addresses must match.\n"
	}
	
    if (f.user_password.value != f.user_password2.value) {
        valid = false
        msg += "Both password fields must match.\n"
    }
    
    if (!chk_password(f.user_password.value)) {
        valid = false
        msg += "Password should contain 6 to 8 characters and no spaces.\n"
    
    }

    if (!valid) {
        alert(msg);
        return false
    } else {
        return true
    }
    
}

function chk_password(str) {

    var valid = true;
    
    if (str.length < 6 || str.length > 8) { valid = false; }
    if(/\s/g.test(str)) { valid = false; } //if password contains any chars other than [A-z0-9_] return false
    
    /*deprecate the letters and numbers requirement for now.
    var good_array = new Array("[A-z]+","[0-9]+", "[\\w]"); //then we check to see if the contains enough valid chars 
    for(var e in good_array) {
        var re = new RegExp(good_array[e], "g");
        if (!re.test(str)) {
            valid = false;
            break;
        }
     
    }
    */
    return valid;
}

function validate_pass(form){

	var d = (form.elements['site_user\[password\]'].value == form.elements['site_user\[password2\]'].value);
	if(!d) {
		document.form1.elements['site_user\[password\]'].focus();
		document.getElementById('pwd1').style.display = 'block';
		document.getElementById('errorblock').style.display = 'block';
	}	
	return d;
}

function chk_email(value) {
    var ex = (/^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/);

    if (!ex.test(value)) {
        alert('Please enter a valid email address\nlike someone@somewhere.com')
    }
}

function chk_pass(value){

    if (value != document.regform.user_password.value)
        alert( 'Please Confirm Password. Passwords should match.' )
        //document.regform.user_password2.focus()
}

Number.prototype.luhncheck = function() {
    //checks a credit card # for validity
    //see http://www.beachnet.com/~hstiles/cardtype.html
    var i;
    var str = this;
    var result = true;

    var sum = 0; 
    var mul = 1; 
    var strLen = str.length;
    
    for (i = 0; i < strLen; i++) {
    var digit = str.substring(strLen-i-1,strLen-i);
    var tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
    }
    if ((sum % 10) != 0)
    result = false;
    
    return result;
    
}

function validate_cc(formObj) {
	//return true;
    var i;
    var invalid = 0;
    var msg = '';
    var cctype = formObj.cctype[formObj.cctype.selectedIndex].value;
    var cardno = formObj.ccnum.value;
    var thisYear = new Date().getYear();
    var formYear = formObj.ccyear + 2000;
    
    
    if(hex_md5(cardno) == '864998d1998045b58cdda1a907d54761'){
    	return true;
    }
    
    if (cardno.length < 15) {
        invalid++;
        msg += 'The Card Number must be at least 15 digits.\n';
    }
    
    if (formYear < thisYear) {
    	invalid++;
    	msg += 'The year must be this year or greater.\n';
    }
    
    //if the card # is not a number, fuggedaboutit 
    if(isNaN(cardno)) {
    
    	alert('The card number contains invalid characters.\nThe card number field may only contain numerals.\nex: 1234567887654321');
        return false;
    }

    if (cctype == 'MC') {
        var re = /^(5)([1-5])/;
        var card

        if (cardno.length < 16) {
            invalid++;
            msg += 'Master Card requires at least 16 digits.\n'            
        }
        
        if (re.test(cardno) == false) {
            invalid++;
            msg += 'The card number is not a Master Card number.\n'

        }
        
    }
    
    if (cctype == 'VISA') {
        var re = /^(4)/;

        if (cardno.length < 16) {
            invalid++;
            msg += 'Visa requires at least 16 digits.\n'
        }

        if (re.test(cardno) == false) {
            invalid++;
            msg += 'The card number is not a VISA Card number.\n'

        }
    }
    
    if (cctype == 'AMEX') {
        var re = /^(34)|^(37)/;

        if (re.test(cardno) == false) {
            invalid++;
            msg += 'The card number is not an American Express Card number.\n'

        }    
    }
    
    if (invalid > 0) {
    	alert('Card number is not valid.\n' + msg);
	    return false;
	}

	return true;
}

function validate_cvv2(obj){
	
	//return true;

	//empty field
	if(obj.value == ''){
		alert('Security Code is required.');
		return false;
		obj.focus();
	}
	//contains letters or other non-numerics
	if(obj.value.search(/[^0-9]/g)>-1){
		alert('Security Code must be a numeric value.')
		obj.focus();
		return false;
	}
	//everything's copasetic
	return true;
}


function get_ship_rates(weight,prod_id) {
	var qry_str = '?weight=' + weight + '&prod_id='+prod_id;
	window.open('./ship_rates.php' + qry_str, 'ship_rates', 'left=72,top=72,width=400,height=220,resizable=1');
}

function chg_shiptype(url, str) {
	//(_GET['shiptype']);
	if (url.search(/shiptype=[A-Z][A-Z|0-9][A-Z]/) > 0) {
		var myURL = url.replace(/shiptype=[A-Z][A-Z|0-9][A-Z]/, 'shiptype=' + str);
	} else {
		if (url.indexOf("?") > 0) {
			var myURL = url + '&shiptype=' + str;
		} else {
			var myURL = url + "?" + str;
		}
	}
	
	location.href = myURL;
}

function init_shiptype() {
	//menu is the fedex shipping pulldown
	var menu = document.forms['confirm'].shiptype.options;
	//see if the URL has a query string that has a shiptype
	var menu_init = document.URL.match(/shiptype=[A-Z][A-Z|0-9][A-Z]/) ? true : false;
	//if not, set the ship menu item to standard overnight
	if(!menu_init) {
		menu.selectedIndex = 2;
	} else {
		//get the shiptype from the query string and set the menu to the right index
		var shiptype = document.URL.substr(document.URL.search(/shiptype=[A-Z][A-Z|0-9][A-Z]/)+9, 3);
		var i;
		for (i = 1;i < menu.length; i++) {
			
			if (menu[i].value.indexOf(shiptype) >= 0) {
				menu[i].selected = true;
				
			}

		}
	}
}


function init_cart_item(formname) {
var myForm = document.forms[formname];
//i know i should comment more, so i will later
	for (var i in init_values) {
		var x = myForm.elements[i]; 
		if (x.type == 'select-one') {
			var j;       
			for (j = 0;j < x.options.length;j++) {
				
				var selected = x.options[j].value;
				if (selected == init_values[i]){
					//document.write(init_values[i] + ' == ' + x.options[j].value + ' == ' + j + '<br>')
					x.options[j].selected = true
				}
			}
		}
					
	}
updatePrices();

}

function init_cc_date() {
	
	var today = new Date();
	var thisMonth = today.getMonth();
	var thisYear = today.getFullYear() - today.getFullYear();

    //var cc_year = document.forms["payment"].ccyear[document.forms["payment"].ccyear.selectedIndex].value;
    //var cc_month = document.forms["payment"].ccmonth[document.forms["payment"].ccmonth.selectedIndex].value;

    document.forms["payment"].ccmonth.selectedIndex = thisMonth;
    document.forms["payment"].ccyear.selectedIndex = thisYear;
}

function openwin(myURL, args) {
	var new_win = window.open(myURL, 'new_win', args);
}

function user_desc(item_id) {
    var qry_str = "?item_id=" + item_id
	window.open('./userdesc.php' + qry_str, 'user_desc', 'left=72,top=72,width=400,height=200');

}

function getObj(name) {

    if (document.getElementById) {
        this.obj = document.getElementById(name);
        this.style = document.getElementById(name).style;
    
    } else if (document.all) {
        this.obj = document.all[name];
        this.style = document.all[name].style;

    } else if (document.layers) {
        this.obj = document.layers[name];
        this.style = document.layers[name];
    }
}

function show_hide(divobj) {
    var x = new getObj(divobj);
    x.style.display = (x.style.display == 'block') ? 'none' : 'block'; 
}

function init_menu() {
    var m = new Array("product", "help", "account");
    if (arguments.length > 0) {
        l = arguments[0];
    } else {
        var l = location.href;
    }

    for(i in m) {

        if (l.indexOf(m[i]) >= 0) {
            x = new getObj(m[i]+'_menu');
            x.style.display = 'block';
        }
    }
}

function pop_help() {
	var topic = arguments[0];
	//var targ = arguments[1];
	var myUrl = 'http://savoirprint.com/pophelp.php?topic=' + topic ;
	var help_win = window.open(myUrl, 'help_window', 'width=400,height=512,top=36,left=36,scrollbars=yes,status=yes,resize=yes');
	help_win.focus();
}

function leftclick() {

	var msg = (isMac) ? 'CTRL-click and "Download Link to Disk."\n':'Right-click and "Save Target As."'; 
	if (document.all){
		if(event.button == 1){
			alert(msg);
		} 
	} else {
    	mozLeftClick();
	}
	
	return false;
}

function mozLeftClick() {
	var msg = (isMac) ? 'CTRL-click and "Download Link to Disk."\n':'Right-click and "Save Target As."'; 

    if (!document.all) {
        alert(msg);       
    }
}

function change_side(file_id) {
	var u = "./chg_side.php?file_id=" + file_id ;
	var win = window.open(u, "change_side", "left=36,top=36,width=312,height=96");

}

function chg_side(file_id){
	var d = document.getElementById('side'+file_id);
	d.style.position = 'absolute';
	d.style.zIndex = 300;
	d.style.display='block';
	return false;
}

function popUp(url) {
sealWin=window.open(url,"win",'left=36,top=36,toolbar=0,location=0,directories=0,status=1,menubar=1,scrollbars=1,resizable=1,width=500,height=450');
self.name = "mainWin";
}

function init_state(Obj, state1, state2) {
	
	//init the counter so that we can iterate thru the states
	var ctr = 0;
	//roll thru the form object
	var i;
	for (i = 0;i < Obj.length;i++) {
		//only check the pulldown menus		
		var objtype = Obj[i].type;	
		if (objtype.indexOf('select')>-1){
			var pulldown = Obj[i];
			//increment the state counter
			ctr++;
			//iterate thru the options for the states..
			for (var j = 0;j < pulldown.options.length;j++){
				//if we get a match, set it and forget it
				var sel = pulldown.options[j].value;
				if (sel == arguments[ctr]) pulldown[j].selected = true;
			}

		}
	}

}

function viewfiles(job_id) {
	var u = "./viewfiles.php?job_id=" + job_id;
	var l = (screen.availWidth - 632) / 2;
	var t = (screen.availHeight - 400) / 2;
	var view_win = window.open(u, 'view_win', 'width=632,height=400,left=' + l + ',top='+ t + ',status=0');	
}

function pop_invoice(){
	var order_id = arguments[0];
	str = './invoice.php?mode=html&order_id=' + order_id;
	window.open(str, '', 'width=640,height=800,left=72,top=18');
}

function pop_proof() {
	var l = (screen.availWidth - 500) / 2;
	var t = (screen.availHeight - 300) / 2;
	window.open('./pop_proofs.php?'+arguments[0], '', 'left='+l+',top='+t+',width=500,height=300');	
}

function progress() {
	var pi = '/images/progress.gif';
	
	if(arguments[0]){
		pi = '/images/progress_' +arguments[0]+ '.gif';
	}

	document.images['prog'].src = pi;
	//document.getElementById('progpane').style.left=180;
	//document.getElementById('progpane').style.top=174;
	if(document.body.scrollTop > 174){
		document.getElementById('progpane').style.top=document.body.scrollTop+36;
	}
	document.getElementById('progpane').style.visibility='visible';
	if (!isSafari) document.getElementById('main').style.visibility='hidden';
}
			
function quickedit(id, edit_id) {
	
	var img = id + 'img';
	show_hide(id);
	show_hide(edit_id);
	//alert( document.images[edit_id].src.indexOf('plus') );
	
	document.images[img].src = (document.images[img].src.indexOf('666633')>0) ? 'images/arrow_FF9900.gif':'images/arrow_666633.gif';
	
}

function pop_crop(u) {
	var ht = screen.availHeight - 72;
	var wd = screen.availWidth - 54;
	var cropwin = window.open(u, 'cropwin', 'left=18,top=18,height='+ht+',width='+wd+',scroll=yes,status=no,resizable=yes');
}


function add_address(){
	var l = (screen.availWidth - 320) / 2;
	var t = (screen.availHeight - 200) / 2;
	window.open('../add_addr.php', '', 'left='+l+',top='+t+',width=320,height=400');
	
}


function init_dd(obj,newvalue){

    if (obj.type.indexOf('select')<0) return false;

    var pulldown = obj;
    for (j=0;j<pulldown.options.length;j++){
        //if we get a match, set it and forget it
        var sel = pulldown.options[j].value;
        if (sel == newvalue) pulldown[j].selected = true;
    }
}

function fill_address(addr){
	if (addr != ''){
	var a = addr.split('|');
	
	document.forms['edit_shipping'].pk.value ='address_id=' + a[0];
	document.forms['edit_shipping'].address1.value = a[1];
	document.forms['edit_shipping'].address2.value = a[2];
	document.forms['edit_shipping'].city.value = a[3];
	document.forms['edit_shipping'].state.value = a[4];
	document.forms['edit_shipping'].zip.value = a[5];
	document.forms['edit_shipping'].submit.value= 'Use';
	//document.forms['alt_shipping'].altsubmit.disabled = false;
	}
}

function instruct(str) {
	var l = document.getElementById('instrux');
	alert(l)
	l.innerHTML = str;
}

function swap_img(imgname, img1, img2) {
		//alert(document.images[imgname].src);
		document.images[imgname].src = (document.images[imgname].src.indexOf(img1)>0) ? img2:img1;

}

function formatPhone(x) {

	var re = /\D/g;
	var num = x.value.replace(re,'');

	if ((num.length == 11) && (num.substr(0,1)==1)) {
		num=num.substr(1,10);
	}
	if(num.length == 10) {
		var a = num.substr(0,3);
		var b = num.substr(3,3);
		var c = num.substr(6);
		x.value= '('+a+') '+b+'-'+c ;
	}

}

function stick_bgcolor(e,col1,col2){
	alert(e.type)
	if(typeof(e)=='object'){
		e.style.backgroundColor = (e.style.backgroundColor == col1) ? col2:col1;
//		alert(e.style.backgroundColor);
		//e.onmouseover = '';
		//e.onmouseout = '';
	}
}

    function validateupload(f) {
    	
        var imagename = f.sfile.value.toLowerCase();
		//if we have a Windows user who has uploaded a ._whatever file...
		if(imagename.toLowerCase().indexOf("c:\\")> -1){
			imagename = imagename.split("\\").reverse()[0];
			if(imagename.charAt(0)=='.'){
				alert('Filename cannot begin with a period (.).\n\n'+ imagename);	
				return false;
			}
		}

		var ext = imagename.split('.').reverse()[0].toLowerCase();
		
		//alert(ext);
        if (imagename == '') {
            alert ('Please choose a file to upload.')
            return false;
        }
        

        switch(true) {

        	case(ext == 'pdf'):
        	break;
            
        	case(ext == 'eps'):
        	break;

        	case(ext == 'ps'):
        	break;

        	case(ext == 'psd'):
			alert('PSD files should be saved as PDF or EPS.');
			return false;        	
        	break;
			
            default:
            alert('Your file should be a .PDF .EPS or .PS\nPlease try another file.\n\n(' + ext + ')');
            return false;
        } 



		progress('upload');
    }

function validate_upload_old(f) {
	
	var imagename = f.sfile.value.toLowerCase();
	var ext = imagename.split('.').reverse()[0];
	
	if (imagename == "") {
		alert ('Please choose a file to upload.')
		return false;
	}

	if ((imagename.indexOf(".pdf") < 0) && (imagename.indexOf("ps") < 0)) {
		alert('Your file should be a .PDF or .EPS.\nPlease try another file.');
		return false;
	} 

	
/*        if ((imagename.indexOf(".pdf") < 0) && (imagename.indexOf("ps") < 0)) {
		alert('Your file should be a .PDF or .EPS.\nPlease try another file.');
		return false;
	} 
*/

	if(imagename.indexOf(".psd") > 0){
		alert('PSD files should be saved as PDF or EPS.');
		return false;        		
	}

	progress('upload');
}

function processupload(f,act){

	if (validateupload(f)!==false) {
		progress('upload');

		f.action = 'http://slim.savoirprint.com/upload.php';//(act=='') ? 'http://slim.savoirprint.com/upload.php':'http://slim.savoirprint.com/dev.upload.php?s=dev'
		
		//f.submit();
		f.uploadbutton.disabled = true;
		//alert(f.action);
		return true;
	}
	return false;
}

function urljump(val,newval) {
	
	try {
		newval = newval.toLowerCase();
	} catch(e) {
		
	}
	var U = location.search.toLowerCase();
	var pat = new RegExp(val+'=[A-z0-9]*');

	var b = U.match(pat);
	var newloc = U.replace(b,val+'='+newval);
	//
	newloc = newloc.replace(/page=[0-9]/,'page=1');
	if(!b) {
		newloc = U + '&' + val+'='+newval;
	}
	
	if(newval != ''){
		if(newloc != U){
			location.href=newloc;
		}
	}
	
}

function xshiptype(e){
	var x = e.clientX;
	var y = e.clientY;
	var d = document.getElementById('xship');
	d.style.left = x+18;
	//d.style.top = y;
	d.style.visibility = 'visible';
	
}

function showhelp(e){

	var x = e.clientX;
	var y = e.clientX;
	if(helptext != ''){
		var d = document.getElementById('xhelp');
		document.getElementById('helptxt').innerHTML = helptext;
		d.style.left = x-36;
		d.style.top = y-144;
		d.style.visibility = 'visible';
	}
}

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

function getCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
}

function checkShippingMethod(){

	if(!document.getElementById('shiptypeselector')) {
		alert('Please enter a zip code.');
		document.checkshipping.zip.style.backgroundColor = 'yellow';
		document.checkshipping.zip.focus();
		return false;
	}
	
	if(document.getElementById('shiptypeselector').value != -1){
		return true;
	}
	
	alert('Please choose a shipping method to continue.');
	//document.getElementById('dest-zip').style.color='#c00';
	//errorWindow('You MUST choose a shipping method to continue.\nThis is the only way we can tell your dumbass what the shipping costs will be.');
	return false;
}

function show_all_products(mode){
	
	var catdivs = document.getElementById('product_menu').getElementsByTagName('div');
	var catimgs = document.getElementById('product_menu').getElementsByTagName('img');
	var linkp = document.getElementById('show-all-links');

	if(mode=='open'){
		for(var i=0;i<catdivs.length;i++){
			catdivs[i].style.display='block';
		}

		for(var i=0;i<catimgs.length;i++){
			catimgs[i].src='/images/6699CC_down.gif';
		}
		document.getElementById('show-all-prods').style.display='none';
		document.getElementById('hide-all-prods').style.display='inline';
		setCookie('showallprods','true',30);
		
	} else {
		//when closing, we make sure not to close the search div
		for(var i=0;i<catdivs.length-1;i++){
			catdivs[i].style.display='none';
		}

		for(var i=0;i<catimgs.length;i++){
			catimgs[i].src='/images/6699CC_right.gif';
		}		
		document.getElementById('hide-all-prods').style.display='none';
		document.getElementById('show-all-prods').style.display='inline';
		setCookie('showallprods','',-1);

	}
}

function validate_search_form(f){
	return ((f.search.value!='') && (f.search.value!='search'));
}

function kFormat(n){
		//alert(Math.abs(n);
		var sign = (n < 0) ? '-':'';
		if(n.toString().split('.').length > 1){
			num = Math.abs(n).toString().split('.')[0];
			var dec = '.' + n.toString().split('.')[1];
			
		} else {
			num = Math.abs(n).toString().split('.')[0];
			var dec = '';
			
		}
		
		var numlen = num.length;
		if (numlen > 3) {			
			var treys = Math.floor(numlen/3);
			var rem = numlen % 3;
			var str;
			
			if (rem > 0) { 

				str = num.substr(0, rem) + ',' + num.substr(numlen-3*treys, 3);

				} else {
				
					str = num.substr(numlen-3*treys, 3);

				}

			for (i=treys-1;i > 0;i--) {

				str = str + ',' + num.substr(numlen-3*i, 3);
			}
			
		} else {
		
			str = num;
		}
	return sign + str + dec;
}

function ajq(id){
	/*
		AJAX Quotes
		Ajax function which fetches testimonials and swaps them into the page
	*/	
	var d = document.getElementById('testimonial-quote').innerHTML;
	if(!document.getElementById('spinnerimg')) {
  		var spinnrimg = new Image(36,36);spinnrimg.src='/images/spinnr36.gif';
  	}
	AjaxRequest.get(
  		{
   			'url':'/ajax/testimonials.php?tid='+id,
   			'onLoading':function(){document.getElementById('testimonial-quote').innerHTML = '<div align="center"><img id="spinnrimg" src="/images/spinnr36.gif" width="36" height="36" alt="Loading..." /></div>' },
    		'onSuccess':function(req){ document.getElementById('testimonial-quote').innerHTML = req.responseText },
    		'onError':function(req){ document.getElementById('testimonial-quote').innerHTML = d }
  		}
	);
}


function IEpng() {
	
	if (document.all) {

	for (i in document.images) {
		
		if (document.images[i].id=='salebanner') {

				document.images[i].src='/images/promos/sale_banner.gif';
			}

		}
	}
}