function showDashboard()
{
    showDiv('dashBoardBack');
    showDiv('popup_outer');
}

function stristr (haystack, needle, bool) {
    // Finds first occurrence of a string within another, case insensitive  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/stristr
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfxied by: Onno Marsman
    // *     example 1: stristr('Kevin van Zonneveld', 'Van');
    // *     returns 1: 'van Zonneveld'
    // *     example 2: stristr('Kevin van Zonneveld', 'VAN', true);
    // *     returns 2: 'Kevin '
    var pos = 0;

    haystack += '';
    pos = haystack.toLowerCase().indexOf( (needle+'').toLowerCase() );
    if (pos == -1){
        return false;
    } else{
        if (bool) {
            return haystack.substr( 0, pos );
        } else{
            return haystack.slice( pos );
        }
    }
}


function hideDashboard()
{
    hideDiv('dashBoardBack');
    hideDiv('popup_outer');
}

function hideDiv(div) {
	document.getElementById(div).style.display = 'none';
}

function showDiv(div) {
	document.getElementById(div).style.display = '';
}

function setVisible(id, visible)
{
    document.getElementById(id).style.display = visible;
}

function createCookie(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 readCookie(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 limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}




function setcookie(name, value, expires, path, domain, secure) 
{
    expires instanceof Date ? expires = expires.toGMTString() : typeof(expires) == 'number' && (expires = (new Date(+(new Date) + expires * 1e3)).toGMTString());
    var r = [name + "=" + escape(value)], s, i;
    for(i in s = {expires: expires, path: path, domain: domain}){
        s[i] && r.push(i + "=" + s[i]);
    }
    return secure && r.push("secure"), document.cookie = r.join(";"), true;
}

function getcookie( check_name ) {
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f
      
    for ( i = 0; i < a_all_cookies.length; i++ )
    {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split( '=' );
            
                
        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
        
        // if the extracted name matches passed check_name
        if ( cookie_name == check_name )
        {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if ( a_temp_cookie.length > 1 )
            {
                cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if ( !b_cookie_found )
    {
        return null;
    }
} 
function setAddtionalOptsVisible(id, visible, plus)
{
    document.getElementById(id).style.display = visible;
    if (visible=="none")
        document.getElementById(plus).innerHTML = '<img src="'+SERVER_NAME+'/themes/general/images/buttons/plus.png" />'; else
        document.getElementById(plus).innerHTML = '<img src="'+SERVER_NAME+'/themes/general/images/buttons/minus.png" />'; 
}

function setJobVisible(idList, plus)
{                  
    var ids = idList.split(",");
                               
    for (var i=0; i<ids.length; i++)
    {             
        var id = ids[i];   
        var visStyle = "";
        if (document.getElementById(id).style.display!="")
          visStyle = ""; else
          visStyle = "none";
        document.getElementById(id).style.display = visStyle;
        if (document.getElementById(id).style.display=="")
            document.getElementById(plus).innerHTML = '<img src="'+SERVER_NAME+'/themes/general/images/buttons/minus.png" />'; else
            document.getElementById(plus).innerHTML = '<img src="'+SERVER_NAME+'/themes/general/images/buttons/plus.png" />';
    } 
}

function setFolderItemVisible(id, plus)
{
    var item = document.getElementById(id);    
    var visible = item.style.display;     

    var visStyle = "";
    if (visible!="")
      visStyle = ""; else
      visStyle = "none";           
    document.getElementById(id).style.display = visStyle;
    if (visible!="")
        document.getElementById(plus).innerHTML = '<img src="'+SERVER_NAME+'/themes/general/images/buttons/minus.png" />'; else
        document.getElementById(plus).innerHTML = '<img src="'+SERVER_NAME+'/themes/general/images/buttons/plus.png" />';

}

function addTextInput(form_name)
{
  var input = document.createElement("input");
  input.name = "email[]";
  input.type = "text";
  input.id = 'id_'+document.forms[form_name].elements.length;
  document.forms[form_name].appendChild(input);
  document.forms[form_name].innerHTML += "<span id=\"remove_id_"+(document.forms[form_name].elements.length-1)+"\"><a onclick=\"removeTextInput('"+form_name+"', '"+'id_'+(document.forms[form_name].elements.length-1)+"'); return false;\" href='#'>-</a><br /></span>\n";
}

function removeTextInput(form_name, id)
{    
  document.forms[form_name].removeChild(document.getElementById(id));
  document.forms[form_name].removeChild(document.getElementById('remove_'+id));
}


function checkShipping(select, zip, get_prices)
{
    document.getElementById(get_prices).disabled = !((document.getElementById(select).value!="") && (document.getElementById(zip).value!=""));
}  

function showHideUpload(detailDiv, imageDiv)
{
    var detail = document.getElementById(detailDiv);
    var image = document.getElementById(imageDiv);
    if (detail.style.display == 'none')
    {
        detail.style.display = '';
        image.innerHTML = '<img src="'+SERVER_NAME+'/themes/general/images/icons/upload/up.gif" align="middle" />';
    } else
    {
        detail.style.display = 'none';
        image.innerHTML = '<img src="'+SERVER_NAME+'/themes/general/images/icons/upload/down.gif" align="middle" />';
    }
}

function popUp(URL) 
{
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=800,height=600,left = 0,top = 0');");
}

function $(name)
{
    return document.getElementById(name);
}

checked = false;
function general_checkAll()
{
	var a = document.getElementById('deletion');

	if (checked == false)
		checked = true;
	else
		checked = false;

	for (var i = 0; i < a.elements.length; i++)
		a.elements[i].checked = checked;
}

function check_all()
{
	x = 0;
	y = true;								
	if (clicks <= 1) 
	{				
		while(y)
		{
			z = document.getElementById('cb_'+x);
			a_span = document.getElementById('cust_order_'+x);						
			if(z != null)
			{
				if(clicks == 0) 
				{
					if(a_span.style.backgroundColor != "")
						z.checked = true;
				} else if (clicks == 1)
					z.checked = true;								
				x++;
			}else
			{
				y=false;
			}
		}
	} else 
	{
		while(y)
		{
			z = document.getElementById('cb_'+x);
			if(z != null)
			{
				z.checked = false;
				x++;
			}else
			{
				y=false;
			}
		}
	}				
	clicks++;				
	if(clicks == 3) clicks = 0;
}

function float_error_correction( number ) 
{
	var num = number;
		num *= 100;
		num = Math.round(num);
		num /= 100;

	return num;
}


function number_format( number, decimals, dec_point, thousands_sep ) 
{
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

function paymentTypeChange(select)
{
//    $('cc_num').setAttribute('cancelValidate', 'true');
//    $('cc_month').setAttribute('cancelValidate', 'true');
//    $('cc_year').setAttribute('cancelValidate', 'true');

	for (var i=0; i<CreditCards.length; i++)
	{
		CreditCards[i]['CreditCardNumber'].setAttribute('cancelValidate', 'true');
		CreditCards[i]['ExpirationMonth'].setAttribute('cancelValidate', 'true');
		CreditCards[i]['ExpirationYear'].setAttribute('cancelValidate', 'true');
		CreditCards[i]['Amount'].setAttribute('cancelValidate', 'true');
	}


    if (select.value == "")
    {
        $('ccFields').style.display = 'none';
    } 

    if (select.value == 'Check')
    {    
        $('ccFields').style.display = 'none';
    } else
    if (select.value == 'Purchase Order')
    {    
        $('ccFields').style.display = 'none';
    } else
    if (select.value == 'Cash')
    {
        $('ccFields').style.display = 'none';
    } else
    if (select.value != '')
    {
//        $('cc_num').setAttribute('cancelValidate', '');
//        $('cc_month').setAttribute('cancelValidate', '');
//        $('cc_year').setAttribute('cancelValidate', '');
        
        for (var i=0; i<CreditCards.length; i++)
		{
			CreditCards[i]['CreditCardNumber'].setAttribute('cancelValidate', '');
			CreditCards[i]['ExpirationMonth'].setAttribute('cancelValidate', '');
			CreditCards[i]['ExpirationYear'].setAttribute('cancelValidate', '');
			CreditCards[i]['Amount'].setAttribute('cancelValidate', '');
		}
        
        
        $('ccFields').style.display = '';
//        if (select.value=="American Express")
//        {
//            $('cc_num').setAttribute('my_maxlength', '15');
//        } else
//        {
//            $('cc_num').setAttribute('my_maxlength', '16');
//        }
//        $('cc_num').onkeypress = ccNumKeyPress;
    }
}


function savedCCChange()
{
    if ($('saved_cc').value=="")
    {
        $('ccFields').style.display = '';
        
        $('payment_type_li').style.display = '';
        $('cc_type').setAttribute('cancelValidate', '');
        $('cc_num').setAttribute('cancelValidate', '');
        $('cc_month').setAttribute('cancelValidate', '');
        $('cc_year').setAttribute('cancelValidate', '');
        
        
        $('cc_type').onchange();
    } else
    { 
        $('ccFields').style.display = 'none';
        
        $('payment_type_li').style.display = 'none';
        $('cc_type').setAttribute('cancelValidate', 'true');  
        $('cc_num').setAttribute('cancelValidate', 'true');
        $('cc_month').setAttribute('cancelValidate', 'true');
        $('cc_year').setAttribute('cancelValidate', 'true');
		
		
    }
    
}

function showHideOrderItems(order_key)
{
    var i;
    for (i=0; i<999; i++)
    {
        var item = $('order_items_'+order_key+'_'+i);
        if (item!=null)
        {
            if (item.style.display == '')
            {
                item.style.display = 'none';
                $('plus_'+order_key).innerHTML = '<img src="'+SERVER_NAME+'/themes/general/images/buttons/plus.png" />';
            } else
            {
                item.style.display = '';
                $('plus_'+order_key).innerHTML = '<img src="'+SERVER_NAME+'/themes/general/images/buttons/minus.png" />';
            }
        } else
        {
            break;
        }
    }
}

function shippingProviderOnChange(select, key)
{
    if (select.selectedIndex==0 || select.value == 'New')
    {
        $('shippingAddress'+key).style.display = 'none';
        $('shippingAddress'+key+'_icon').style.display = 'none';
        $('shippingAddress'+key+'_icon_text').style.display = 'none';
        $('shippingInfo'+key).style.display = 'none';
    }
    
    if (select.selectedIndex>0 && select.value != 'New')
    {
        $('shippingAddress'+key).style.display = '';
        $('shippingAddress'+key+'_icon').style.display = '';
        $('shippingAddress'+key+'_icon_text').style.display = '';
        $('shippingInfo'+key).style.display = '';
    }
    
    if (select.options[select.selectedIndex].text == 'UPS')
    {
        $('shippingInsurance'+key).style.display = '';
    } else
    {
        $('shippingInsurance'+key).style.display = 'none';
    }
	
	if(select.value == 'New')
	{
		eval('newButtonClicked('+key+');');
		$('btnEdit').style.display = 'none';
	}else{
		$('addShippingDiv'+key).style.display = 'none';
	}
    
    if (select.options[select.selectedIndex].text == 'My Ship Account')
	{
        $('shipping_account_span').style.display = '';
		$('shipping_account').setAttribute('validate', 'isEmpty');
		$('shipping_account').setAttribute('vmessage', '');
    } else
    {
        $('shipping_account_span').style.display = 'none';
        $('shipping_account').value = '';
		$('shipping_account').removeAttribute('validate');
		$('shipping_account').removeAttribute('vmessage');		
    }
    
    eval('updateShippingOptions'+key+'();');
    //eval('getPrices'+key+'();');
}

function shippingAddressOnChange(select, key)
{

    {
        $('addShippingDiv'+key).style.display = 'none'; 
        $('tr2'+key).style.height = '200px';
    } 
    
    if (select.selectedIndex==0)
    { 
        $('btnEdit').style.display = 'none';
    }
    
    if (select.selectedIndex>0) 
    {
        $('btnEdit').style.display = '';
    } 
    
    eval('updateShippingOptions'+key+'();');
	//eval('getPrices'+key+'();');
    
    makeRequest(SERVER_NAME+'/orders/get-shipping-more-info-ajax.html?ajax=true&value='+select.value+'&key='+key, 'shippingInfo'+key); 

    
}

function displayCustomPriceField(id, value)
{
	if (value==1) 
		$(id).style.display = ''; else 
		$(id).style.display = 'none'; 
}

function updateStatistics()
{
    if ($('updateStatisticsLink').innerHTML == 'Show Working Days')
    {
        $('calcWorkingDays1').style.display = '';
        $('calcAllDays1').style.display = 'none';
        
        $('calcWorkingDays2').style.display = '';
        $('calcAllDays2').style.display = 'none';
        
        $('calcWorkingDays3').style.display = '';
        $('calcAllDays3').style.display = 'none';
        
        $('updateStatisticsLink').innerHTML = 'Show Calendar Days';
    } else
    {
        $('calcWorkingDays1').style.display = 'none';
        $('calcAllDays1').style.display = '';
        
        $('calcWorkingDays2').style.display = 'none';
        $('calcAllDays2').style.display = '';
        
        $('calcWorkingDays3').style.display = 'none';
        $('calcAllDays3').style.display = '';
        
        $('updateStatisticsLink').innerHTML = 'Show Working Days';
    }
}

function getPageSizeWithScroll()
{
	if (window.innerHeight && window.scrollMaxY) {// Firefox
		yWithScroll = window.innerHeight + window.scrollMaxY;
		xWithScroll = window.innerWidth + window.scrollMaxX;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		yWithScroll = document.body.scrollHeight;
		xWithScroll = document.body.scrollWidth;
	} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
		yWithScroll = document.body.offsetHeight;
		xWithScroll = document.body.offsetWidth;
  	}
	arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);
	//alert( 'The height is ' + yWithScroll + ' and the width is ' + xWithScroll );
	return arrayPageSizeWithScroll;
}


function editButtonClicked(id)
{
    var a = document.createElement('a');
    a.setAttribute('href', SERVER_NAME+'/orders/edit-shipping-address.html?ajax=true&id='+id);
 //   alert(a.getAttribute('href'));
    a.appendChild(document.createTextNode("Edit"));
    a.rel = "width=465;height=400;";
    Shadowbox.open(a);
    
    return false;
}
function ccNumKeyPress(e)
{
    if (window.event) 
    {
        if ( (window.event.keyCode == 8) || (window.event.keyCode == 127) ) return true; 
    }  else
    {
        if ( (e.which == 8) || (e.which == 127) ) return true;
    }
    
    return (this.getAttribute('my_maxlength') > this.value.length ); 
}

function showHideExactSize(key)
{  
    if ( (key=='')  )
    { 
        var papertype = $('Paper_Type');   
        var exactsize = $('Must_Be_Exact_Trim_Size');
    } else
    {
        var papertype = $(key); 
        var parts = key.split('^');
        var exactsize = $('Must_Be_Exact_Trim_Size^'+parts[1]);
    }

    if ( (papertype!=null) && (exactsize!=null) )
    { 
        var selected_papertype = papertype.options[papertype.selectedIndex].text;
        if ((selected_papertype=='100# Gloss Text') && (papertype.selectedIndex != 0))
        {
            exactsize.options[0].setAttribute('disabled', 'disabled');
            if (exactsize.selectedIndex==0) exactsize.selectedIndex = 1;
        }
		else
        {
            exactsize.options[0].removeAttribute('disabled');
			// if (exactsize.selectedIndex==1) exactsize.selectedIndex = 0;   //Commented resetting the value back to No, because it was always resetting when other than 100# is selected
        }
        
        exactsize.onchange();
    }
}

function showHideScoring(key)
{  
    if ( (key=='')  )
    { 
        var folding = $('Folding');   
        var scoring = $('Scoring');
    } else
    {
        var folding = $(key); 
        var parts = key.split('^');
        var scoring = $('Scoring^'+parts[1]);
    }

    if ( (folding!=null) && (scoring!=null) )
    { 
        var selected_folding = folding.options[folding.selectedIndex].text;
        if (selected_folding!='No Folding')
        {
            scoring.options[0].setAttribute('disabled', 'disabled');
            if (scoring.selectedIndex==0) scoring.selectedIndex = 1;
        } else
        {
            scoring.options[0].removeAttribute('disabled');
        }
        
        scoring.onchange();
    }
}

function showHideUVCoatingOption(mailing, uv, key)
{   
    var uv_select = $(uv); 
    var mailing_select = $(mailing);
    var exact_size = $('Must_Be_Exact_Trim_Size');
    if (exact_size==null)
    {
        exact_size = $('Must_Be_Exact_Trim_Size^'+key);
    }

	if (uv_select!=null)
    {  
        if (mailing_select.options[mailing_select.selectedIndex].text == "Yes Mailing Services")
        {
                        
			uv_select.options[1].setAttribute('disabled', 'disabled');
            if (uv_select.selectedIndex==1) uv_select.selectedIndex = 2;
            
			if (exact_size!=null)
            {
                for (var i=0; i<exact_size.length; i++)
                if (exact_size.options[i].text=="Yes")
                    exact_size.selectedIndex = i;
            }
            
        } else
        {
            uv_select.options[1].removeAttribute('disabled');
        }
               
        
    }
}

function toggle_visibility(id) {
		var e = document.getElementById(id);
			   if(e.style.display == '')
				  e.style.display = 'none';
			   else
				  e.style.display = '';
}
