
// Generate Username/Password

function login_populate( form, populate_flag, username, password ) {
	if( populate_flag ) {
		if( !form.username.value )
			form.username.value = username;
		if( !form.password.value )
			form.password.value = password;
		disable = false;
	}
	else disable = true;
	
	form.username.disabled = disable;
	form.password.disabled = disable;
}


// Minute/Second Timer

function timer_start( field ) {
	timer_start = new Date();
	field.value = "0:00";
	timer_update(field);
}

function timer_update( field ) {
	var timer_now = new Date();
	var timer_diff = timer_now - timer_start;
   
	var mins = Math.floor(timer_diff/( 60 * 1000 ));
	var secs = Math.floor(timer_diff/1000)%60;

	document.artwork_upload.timer_elapse.value = mins+":"+leadingZero(secs);
	setTimeout("timer_update('"+field+"')", 1000);
}


// Number Manipulation

function leadingZero(x){
	return (x>9)?x:'0'+x;
}

function commify(Num,Prec) {
	var Num = Num.toString();
	var newNum = "";
	var newNum2 = "";
	var count = 0;
	var end = "";

	//check for decimal number
	if (Num.indexOf('.') != -1){ //number ends with a decimal point
		var a = Num.split("."); 
		Num = a[0]; //the part we will commify
		var end = a[1] //the decimal place we will ignore and add back later
	}
	
	//this loop actually adds the commas 
	for (var k = Num.length-1; k >= 0; k--){
		var oneChar = Num.charAt(k);
		if (count == 3){
			newNum += "," + oneChar;
			count = 1;
			continue;
		}
		else {
			newNum += oneChar;
			count++;
		}
	} //but now the string is reversed!

	//re-reverse the string
	for (var k = newNum.length-1; k >= 0; k--){
		var oneChar = newNum.charAt(k);
		newNum2 += oneChar;
	}
	
	// add decimal ending from above
	newNum2 += ".";
	if( Prec ) {
		for( i = 0; i < Prec; i++ )
			newNum2 += end.charAt(i) ? end.charAt(i) : '0';
	}
	else if( end != 0 ) newNum2 += end;
	return newNum2;
}


/* Date Functions */

function date_diff( date_from, date_to ) {
	milliseconds = Math.abs( date_from.getTime() - date_to.getTime() );
	return milliseconds/1000/60/60/24;
}



/**
 * DHTML textbox character counter (IE4+) script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

function taLimit() {
	var taObj=event.srcElement;
	if (taObj.value.length==taObj.maxLength*1) return false;
}

function taCount_innerText(visCnt) { 
	var taObj=event.srcElement;
	if (taObj.value.length>taObj.maxLength*1) taObj.value=taObj.value.substring(0,taObj.maxLength*1);
	if (visCnt) visCnt.innerText=taObj.maxLength-taObj.value.length;
}
function taCount_input(visCnt) { 
	var taObj=event.srcElement;
	if (taObj.value.length>taObj.maxLength*1) taObj.value=taObj.value.substring(0,taObj.maxLength*1);
	if (visCnt) visCnt.value=taObj.maxLength-taObj.value.length;
}
function zip_checker(form, obj, event_new, name_status, zip_check_flag) {
	if(( event_new.keyCode >= 48 && event_new.keyCode <= 57 )||( event_new.keyCode >= 96 && event_new.keyCode <= 105 )) {
		if( obj.value.length == 5 ) {
			document.getElementById(name_status).innerHTML = 'Validating...';
			//document.co_zip_check.value = 1;
			document.forms[form].elements[zip_check_flag].value = 1;
			document.forms[form].submit();
		} else {
			document.getElementById(name_status).innerHTML = '';
		}
	}
}

// Printing
function print_page(print_dialog) {
  //save existing user's info
  var h = factory.printing.header;
  var f = factory.printing.footer;
  //hide the button
  document.all("print_button").style.visibility = 'hidden';
  //set header and footer to blank
  factory.printing.header = "";
  factory.printing.footer = "";
  //print page without prompt
  factory.DoPrint(print_dialog);
  //restore user's info
  factory.printing.header = h;
  factory.printing.footer = f;
  //show the print button
  document.all("print_button").style.visibility = 'visible';
}


// Window Size

function getWindowSize() { 
	var e = new Object(); 
	if(window.self && self.innerWidth) { 
		e.width = self.innerWidth; 
		e.height = self.innerHeight; 
	} 
	else if(document.documentElement && document.documentElement.clientHeight) { 
		e.width = document.documentElement.clientWidth; 
		e.height = document.documentElement.clientHeight; 
	}
	else {
		e.width = document.body.clientWidth; 
		e.height = document.body.clientHeight; 
	} 
	return e;
}


// DIV Layers

 // 1 visible, 0 hidden
function toggle_visibility(obj, iState) {
  //NN4+
  if(document.layers) {
     document.layers[obj].visibility = iState ? "show" : "hide";
  }
  //gecko(NN6) + IE 5+
  else if(document.getElementById) {
    var obj = document.getElementById(obj);
    obj.style.visibility = iState ? "visible" : "hidden";
  }
  // IE 4
  else if(document.all) {
    document.all[obj].style.visibility = iState ? "visible" : "hidden";
  }
}

function toggle_display(div_id, disp) {
	// IE6 doesn't like the onChange tag. Use onClick instead
	//NN4+
	if(document.layers) {
		var obj = document.layers[div_id];
		obj.style.display = disp == 1 ? "block" : "none";
	}
	//gecko(NN6) + IE 5+
	else if(document.getElementById) {
		var obj = document.getElementById(div_id);
		obj.style.display = disp == 1 ? "block" : "none";
	}
	// IE 4
	else if(document.all) {
		var obj = document.all[div_id];
		obj.style.display = disp == 1 ? "block" : "none";
	}
}


// AM/PM Time Functions

ampm_touched = false;

function update_ampm(form_hour,form_ampm) {
	if( !ampm_touched ) {
		if( form_hour.options[form_hour.selectedIndex].value >= 9 && form_hour.options[form_hour.selectedIndex].value != 12 ) {
			setDefaultByValue(form_ampm, 'am');
		} else {
			setDefaultByValue(form_ampm, 'pm');
		}
	}
}

function set_ampm() {
	ampm_touched = true;
}

// Functions for checkbox manipulation

function checkbox_check( form, name, check_value ) {
	var forminputs = document.forms[form].getElementsByTagName('input');
	for (i = 0; i < forminputs.length; i++) {
		// regex here to check name attribute
		var regex = new RegExp(name, "i");
		if (regex.test(forminputs[i].getAttribute('name'))) {
			if (check_value == '1') {
				forminputs[i].checked = true;
			} else {
				forminputs[i].checked = false;
			}
		}
	}
}

function checkbox_check_value( form, value, check_value ) {
	var forminputs = document.forms[form].getElementsByTagName('input');
	for (i = 0; i < forminputs.length; i++) {
		// regex here to check name attribute
		var regex = new RegExp(value, "i");
		if (regex.test(forminputs[i].getAttribute('value'))) {
			if( check_value == '1' ) {
				forminputs[i].checked = true;
			} else {
				forminputs[i].checked = false;
			}
		}
	}
}

function checkbox_count( form, name ) {
	var count = 0;
	var forminputs = document.forms[form].getElementsByTagName('input');
	for (i = 0; i < forminputs.length; i++) {
		// regex here to check name attribute
		var regex = new RegExp(name, "i");
		if (regex.test(forminputs[i].getAttribute('name'))) {
			if( forminputs[i].checked ) {
				count++;
			}
		}
	}
	return count;
}

/* Text Area box manipulation */

function textarea_row_adjust( textarea, text_width ) {
	text_width = text_width || 1;
	var agt=navigator.userAgent.toLowerCase(); 
	a = textarea.value.split('\n');
	b=1;
	for( x=0;x < a.length; x++ ) {
		if( a[x].length*text_width >= textarea.cols )
			b+= Math.floor( a[x].length*text_width / textarea.cols );
	}
	//alert(b+" "+textarea.rows);
	b+= a.length;
	if( b > textarea.rows && agt.indexOf('opera') == -1 )
		textarea.rows = b;
}

function textarea_count( form, name ) {
	var count = 0;
	var forminputs = document.forms[form].getElementsByTagName('input');
	for (i = 0; i < forminputs.length; i++) {
		// regex here to check name attribute
		var regex = new RegExp(name, "i");
//alert(forminputs[i].getAttribute('name')+":"+forminputs[i].value);
		if (regex.test(forminputs[i].getAttribute('name'))) {
			if( forminputs[i].value ) {
//alert(forminputs[i].getAttribute('name')+":"+forminputs[i].value);
				count+= Math.floor( forminputs[i].value );
			}
		}
	}
	return count;
}

/* radio value manipulation */

function radio_get_value( radioObj ) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function radio_set_value( radioObj, newValue ) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}


/*
JavaScript functions for client-side manipulation of HTML listboxes.
Works on both NetScape (4.0+) and IE (4.0+).
*/
function clearList(list) 
    {
    var i = 0;
    var o = list.options;

    for (i = o.length; i >= 0; --i)
		o[i] = null;
    list.disabled = true;
    }

function addElement(list, text_in, value_in)
    {
    var o = list.options;
    var nIdx;
    if (o.length < 0) //IE for Mac 4.5 sets length to -1 if list is empty
        nIdx = 0;
    else
        nIdx = o.length;
		
	o[nIdx] = new Option(text_in, value_in);
    list.disabled = false;
    }

function addElementAtPos(list, pos, text_in, value_in)
    {
    var o = list.options;
    var nIdx = 0;

    if ((pos < 0) || (pos > o.length))
        return;

    addElement(list, '', '');
    for (nIdx = o.length - 1; nIdx > pos; nIdx--)
    {
        o[nIdx].text = o[nIdx - 1].text;
        o[nIdx].value = o[nIdx - 1].value;
    }
    o[pos] = new Option(text_in, value_in);
    list.disabled = false;
    }

function setDefaultByText(list, text_in)
    {
    with (list)
        {
        for (var i = 0; i < (options.length); i++)
             {
             if (options[i].text == text_in)
                 {
                 selectedIndex = i;
                 return;
                 }
             }
        }
    }

function setDefaultByValue(list, value_in)
    {
    with (list)
		{
        for (var i = 0; i < (options.length); i++)
             {
             if (options[i].value == value_in)
                 {
				 selectedIndex = i;
                 return;
                 }
             }
        }
    }


// Forms

function link_form(form) {
	form.target='_blank';
	form.submit();
	return true;
}


// Pop-Up Window

var window_name = Math.floor(Math.random()*9999);

function popParentRefresh() {
  window.opener.parent.location.reload();	
}

function popClose() {
	window.opener.parent.location.reload();
	window.close();
}

function popCloseRedirect( theURL ) {
  window.opener.parent.location = theURL;
  window.close();
}

function popWinQuick( theURL ) {
  popWinName( theURL, window_name );
  window_name++;
}

function popWinName( theURL, winName ) {
  popWin( theURL, winName, 700, 600, 1, 0, 0, 0, 1 );
}

function popWinSize( theURL, width, height ) {
  popWin( theURL, window_name, width, height, 1, 0, 0, 0, 1 );
  window_name++;
}

function popWinSizeTools( theURL, width, height ) {
  popWin( theURL, window_name, width, height, 1, 0, 1, 0, 1 );
  window_name++;
}

function popWin( theURL, winName, width, height, scrollBars, toolBar, menuBars, addressField, resizable ) {
  var features =
    'width='        + width +
    ',height='      + height +
    ',scrollbars='  + scrollBars +
    ',toolbar='     + toolBar +
    ',menubar='     + menuBars +
    ',location='    + addressField +
    ',resizable='   + resizable +
    ',status=0';
  var winRef = window.open( theURL, winName, features);
  winRef.focus();
}


function setcookie(name, value, expires, path, domain, secure) {
    var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
	curCookie += ";";
//        alert(curCookie);
    if (value) document.cookie = curCookie.replace('257C', '7C');
}

// Image Rollovers by Dreamweaver

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


// cookiez by joe
var affinfo;
var referer = document.referrer;
var expdate = new Date ();
var uniquid =(expdate.getTime()+""+Math.floor((Math.random()*8999)+1000));
var expired = new Date(expdate.getTime() - 48 * 60 * 60 * 1000);
expdate.setTime(expdate.getTime() + (86400 * 30));

// ensure cookie is not set again
if (document.cookie.length < 43) {
    if ((!document.cookie.match("affinfo=")) || (document.cookie.match("affinfo=") == "affinfo=")) {
		if (document.URL.match("affid=")) {
            // grab referral part of URL "affid=1012|PR7004001"
			affinfo = document.URL.substr(document.URL.indexOf("affid"));
			if( affinfo.lastIndexOf("|") == -1 || affinfo.lastIndexOf("|") == affinfo.length-1 )
				affinfo += "|0|" + uniquid + "|" + referer; // affiliate known, ad unknown
			else
				affinfo += "|" + uniquid + "|" + referer; // affiliate and ad known
            setcookie('affinfo', affinfo.replace("affid=", ""), expdate, '/');
        } else if (!document.cookie.match("affinfo=")) {
            affinfo = "0|0|" + uniquid + "|" + referer; // affiliate and ad unknown
            setcookie('affinfo', affinfo, expdate, '/');
        }
    }
}
