



var myShowForm=false;
var myContentForm = false;
var form_element_prefix = "ctl00_Main_";
var GB_ROOT_DIR = "http"+(("https:" == document.location.protocol) ? "s" : "")+"://"+greyboxPath(document.location.href)+"/admin/code/JavaScript/greybox/";
document.writeln('<!--//'+GB_ROOT_DIR+'-->')

function ShowContent(d, e) 
{
	if (document.getElementById(d).style.display == "inline") {
		document.getElementById(d).style.display ="none"
	}
	else
	{
		document.getElementById(d).style.display ="inline";
	}
	if (e != '') 
	{
		document.getElementById(e).style.display ="none";
	}
}
function HideContent(d) {
	document.getElementById(d).style.display ="none";
}
function ReverseContentDisplay(d)
{
	if(document.getElementById(d).style.display == "none") 
	{
		document.getElementById(d).style.display = "";
	}
	else 
	{ 
	document.getElementById(d).style.display = "none"; 
	}
}

function greyboxPath(url_)
{
	url_ = (url_.indexOf('http://') > -1) ? url_.substring(7,url_.length) : url_.substring(8,url_.length);
	url_ = url_.substring(0,url_.indexOf('/'))
	return url_;
}


function ManageContent(Action,thisIDname,thisIDvalue,PartNumber,FileName,K_){
			
	if (myContentForm){
		myContentForm.close();
	}
	
	if(Action=="D"){
		if(document.getElementById('current_content_container')){
			document.getElementById('current_content_container').value="|"+thisIDname+","+thisIDvalue+","+PartNumber+","+K_+"|";
			return false;
		}else{
			return false;
		}
	}
	
	K_ = K_ ? K_ : 0;

//	myContentForm = window.open('/admin/code/Content/ContentForm/ContentForm_'+FileName+'_'+PartNumber+'.aspx?A='+Action+'&B='+thisIDname+'&C='+thisIDvalue+'&D='+PartNumber+'&E='+K_,'ContentManage','toolbars=no,scrollbars=yes,status=yes,location=no,width=600,height=575,resizable=yes,left=10,top=10,postionx=10,positiony=10');
	GB_showCenter('Manage Content','/admin/code/Content/ContentForm/ContentForm_'+FileName+'_'+PartNumber+'.aspx?A='+Action+'&B='+thisIDname+'&C='+thisIDvalue+'&D='+PartNumber+'&E='+K_,700,900);


}


function ShowAddUpdate(FileName,Action,Args,PopUp){

	var isMac = navigator.userAgent.indexOf('Mac') != -1 
		
	if (isMac){
		if (Args){
			if(Args.substring(1,1) != "&"){
				Args = '&'+Args
			}
		}else{
			Args = ''
		}	
	}else{
		if ((Args != undefined) && (Args != '')){
			if(Args.substring(1,1) != "&"){
			Args = '&'+Args
			}
		}else{
			Args = ''
		}
	}
	
	var formName = 'formName'

	var xtraArgs = document.location.href;
	if(xtraArgs.indexOf('?')>0){
		xtraArgs = xtraArgs.substring(xtraArgs.indexOf('?')+1,xtraArgs.length);
		if(Action=="U" || Action=="S" &&Args.indexOf('PK=')>-1){
			xtraArgs=xtraArgs.replace(/PK=[\S]*?&/gi,"");
		}
	}else{
		xtraArgs = "";
	}

	if(Args!=""&&xtraArgs!=""){xtraArgs='&'+xtraArgs;}
	Args += xtraArgs; 
	if(Args!=""&&Args.substring(0,1)!='&'){
		Args='&'+Args;
	}
	if(myShowForm){
		myShowForm.close();
	}
	


	var prefixPath = "/admin/code/AddUpdatePages/";	
	if(PopUp){
		prefixPath = "/admin/code/PopUp/";
	}

//	myShowForm = window.open(prefixPath+FileName+'?A='+Action+Args,formName,'toolbars=no,scrollbars=yes,status=yes,location=no,width=600,height=575,resizable=yes,left=10,top=10,postionx=10,positiony=10');
//	myShowForm.focus();
	
	GB_showCenter('Manage Form', prefixPath+FileName+'?A='+Action+Args,700,900);

}


function ShowPopUp(FileName,useGreyBox,width,height){
	var formName = 'formName'+FileName.replace(/[^a-zA-Z]/gi,"");
	var prefixPath = "/admin/code/PopUp/";

	if (useGreyBox){
		//alert(width);
		GB_showCenter('',prefixPath+FileName,height,width);
	}else{
		var myPopUpForm = window.open(prefixPath+FileName,formName,'toolbars=no,scrollbars=yes,status=yes,location=no,width=900,height=625,resizable=yes,left=10,top=10,postionx=10,positiony=10');
		myPopUpForm.focus();
	}
}




function closeForm(){
	try{
		parent.parent.GB_hide();
	} catch(err){
		opener.document.location.href=opener.document.location.href;
		window.close();
	}
}

function RunOrderByColumnName(ColumnName){

	if(document.getElementById('ctl00_Main_OrderByColumnName')){
		var currOrderByColumnName = document.getElementById('ctl00_Main_OrderByColumnName')
		if(currOrderByColumnName.value==ColumnName+' ASC'){
			currOrderByColumnName.value=ColumnName+' DESC';
		}else{
			currOrderByColumnName.value=ColumnName+' ASC';
		}
			
	}
	document.forms[0].submit();
}



function showPrint(PrintKey){
	var myPrint = window.open('/admin/code/Print/ManagePrint.aspx?A='+PrintKey,PrintKey,'toolbars=yes,scrollbars=yes,status=yes,location=no,width=650,height=575,resizable=yes,left=10,top=10,postionx=10,positiony=10');
	myPrint.focus();

}

function showPrintPage(Page){
	var URL = "/Admin/Code/PopUp/PopUp_Print.aspx?page="+Page;
	GB_showCenter('Print Page',URL,null,778);

}




function ChangePage(Action,To,Step){
	var regRetVal = new RegExp(/retVal=[\S|\s]*/gi);
	var regURL = new RegExp(/http\S*:\/\/[\S]*?\.[\S]*?\//i);
	var retVal = regRetVal.exec(document.location.href); 
	retVal = retVal ? retVal[0] : "";

	var baseURL = regURL.exec(document.location.href);
	baseURL = baseURL[0];
	var currPage = document.location.href;
	currPage = currPage.substring(baseURL.length-1,currPage.length);
	Step = Step ? Step : 0;


	if(Action=="BACK"){
		var itemName="";itemValue="";itemArray = new Array();
		retVal = retVal.replace(/\%3a/gi,":");
		retVal = retVal.replace(/\%7C/gi,"|");
		if(retVal.substring(0,7)=='retVal='){
			retVal = retVal.substring(7,retVal.length);
		}
		var retHistory = retVal.split(/\|/gi);
		for(k=0;k<retHistory.length;k++){
			itemName = retHistory[k].substring(0,retHistory[k].indexOf(':'))
			itemValue = retHistory[k].substring(retHistory[k].indexOf(':')+1,retHistory[k].length);
			itemArray[itemName] = URLDecode(itemValue);
		}
		

		if(itemArray.length>=Step){
			if(itemArray[Step].indexOf('&retVal=')>0){
				retVal = itemArray[Step];
				retVal = retVal.substring(retVal.indexOf('&retVal=')+8,retVal.length)
				itemArray[Step] = itemArray[Step].substring(0,itemArray[Step].indexOf('&retVal=')+7)+"="+URLEncode(retVal)+'|';
			} 
			document.location.href = itemArray[Step];
		}else{
			alert('Could not find Step in the retVal of the previous querystring');
			return false;
		}
	
	}else if(Action=="NEXT"){
		// append to retVal if applicable		
		if(retVal){
			currPage = (currPage.substring(currPage.length-1,currPage.length)!='|') ? currPage+'|' : currPage;
			retVal+=Step+":"+URLEncode(currPage)
			if (To.indexOf("?")==-1){
				To+='?'+retVal;
			}else{
				To+="&"+retVal;
			}
			document.location.href = To;
		}else{
			retVal = "&retVal="+Step+":"+URLEncode(currPage)+'|'
			To+=retVal;
			document.location.href = To;
		}	
		
	}else{
		alert('No Action Specified: BACK OR NEXT');
		return false;
	}

}



function Get_Cookie(name) { 
   var start = document.cookie.indexOf(name+"="); 
   var len = start+name.length+1; 
   if ((!start) && (name != document.cookie.substring(0,name.length))) return null; 
   if (start == -1) return null; 
   var end = document.cookie.indexOf(";",len); 
   if (end == -1) end = document.cookie.length; 
   return unescape(document.cookie.substring(len,end)); 
} 

function Set_Cookie( name, value, expires, path, domain, secure ){
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct 
expires time, the current script below will set 
it for x number of days, to make it for hours, 
delete * 24, for minutes, delete * 60 * 24
*/

if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
( ( path ) ? ";path=" + path : "" ) + 
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}


function Delete_Cookie(name,path,domain) { 
   if (Get_Cookie(name)) document.cookie = name + "=" + 
      ( (path) ? ";path=" + path : "") + 
      ( (domain) ? ";domain=" + domain : "") + 
      ";expires=Thu, 01-Jan-70 00:00:01 GMT"; 
} 





function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}


function URLDecode (encodedString) {
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%[^%]{2})/;
  while ((match = myregexp.exec(output)) != null
             && match.length > 1
             && match[1] != '') {
    binVal = parseInt(match[1].substr(1),16);
    thisString = String.fromCharCode(binVal);
    output = output.replace(match[1], thisString);
  }
  return output;
}




//Drop-Down Menu Start

var DDSPEED = 2;
var DDTIMER = 2;

// main function to handle the mouse events //
function ddMenu(id,d){
  var h = document.getElementById(id + '-ddheader');
  var c = document.getElementById(id + '-ddcontent');
  clearInterval(c.timer);
  if(d == 1){
    clearTimeout(h.timer);
    if(c.maxh && c.maxh <= c.offsetHeight){return}
    else if(!c.maxh){
      c.style.display = 'block';
      c.style.height = 'auto';
      c.maxh = c.offsetHeight;
      c.style.height = '0px';
    }
    c.timer = setInterval(function(){ddSlide(c,1)},DDTIMER);
  }else{
    h.timer = setTimeout(function(){ddCollapse(c)},50);
  }
}

// collapse the menu //
function ddCollapse(c){
  c.timer = setInterval(function(){ddSlide(c,-1)},DDTIMER);
}

// cancel the collapse if a user rolls over the dropdown //
function cancelHide(id){
  var h = document.getElementById(id + '-ddheader');
  var c = document.getElementById(id + '-ddcontent');
  clearTimeout(h.timer);
  clearInterval(c.timer);
  if(c.offsetHeight < c.maxh){
    c.timer = setInterval(function(){ddSlide(c,1)},DDTIMER);
  }
}

// incrementally expand/contract the dropdown and change the opacity //
function ddSlide(c,d){
  var currh = c.offsetHeight;
  var dist;
  if(d == 1){
    dist = (Math.round((c.maxh - currh) / DDSPEED));
  }else{
    dist = (Math.round(currh / DDSPEED));
  }
  if(dist <= 1 && d == 1){
    dist = 1;
  }
  c.style.height = currh + (dist * d) + 'px';
  c.style.opacity = currh / c.maxh;
  c.style.filter = 'alpha(opacity=' + (currh * 100 / c.maxh) + ')';
  if((currh < 2 && d != 1) || (currh > (c.maxh - 2) && d == 1)){
    clearInterval(c.timer);
  }
}

//Drop-Down Menu Stop
function starFill(i)
{
    for(k=1;k<i+1;k++){
        document.getElementById('RateStar'+k).className = 'starbtnhover';
    }
}

function starClear()
{
    for(k=1;k<6;k++){
        document.getElementById('RateStar'+k).className = 'starbtn';
    }
}

function starFill29(i, j)
{
    for(k=1;k<i+1;k++){
        document.getElementById('RateStar'+k+'_'+j).className = 'starbtnhover29';
    }
}

function starClear29(j)
{
    for(k=1;k<6;k++){
        document.getElementById('RateStar'+k+'_'+j).className = 'starbtn29';
    }
}
function ValidateComment(txt)   
    {   
        if(txt.value.length<20)   
        {   
            alert("Minimum 20 chars required")   
            txt.focus();    
			return false
        }   
		return true
    }   
function showFacebook(){
	var ref = URLEncode(document.location.href);
	document.location.href='/Facebook/?ref='+ref;
	return false;
}




function hideItem(id,n){
	$('#'+id).fadeOut(n ? n : 400);	
}

function showItem(id,n){
	$('#'+id).fadeIn(n ? n : 400);	
}

function getprefix(){
	var a = document.getElementsByTagName('input');
	for(j=0;j<a.length;j++){
		var i = a[j];
		if(i.id.indexOf('ctl00_')>-1){
			var p = i.id.substring(0,i.id.lastIndexOf('_')+1); 
			return p;
		}
	}
		
}



function calcCIMOrder(){
	var prefix = getprefix();
	var t = 0;
	// set fields
	var f = new Array();
	f["shipType"] = document.getElementById(prefix+'ShippingType');
	f["shipCost"] = document.getElementById(prefix+'Shipping');
	f["taxAmount"] = document.getElementById(prefix+'Tax');
	f["taxRate"] = document.getElementById(prefix+'TaxRate');
	f["discount"] = document.getElementById(prefix+'CouponAmount');
	f["subTotal"] = document.getElementById(prefix+'SubTotal');
	f["totalAmount"] = document.getElementById(prefix+'TotalAmount');
	
	// must be zero
	var isZero = new Array("shipCost","taxAmount","taxRate","discount","subTotal");
	for(z=0;z<isZero.length;z++){
		if(f[isZero[z]]){
			f[isZero[z]].value = isNumber(f[isZero[z]].value)  ? parseFloat(f[isZero[z]].value) : 0;
		}
	}
	
	// set shipping
	if(f["shipType"]){
		f["shipCost"].value = f["shipType"].value;	
	}
	// calc tax
	if(f["taxRate"]&&f["taxAmount"]){
		f["taxAmount"].value = parseFloat(f["subTotal"].value * f["taxAmount"].value);
	}


	// sub total - discount + shipping + tax = total amount	
	t = f["subTotal"].value;

	// - discount
	t = f["discount"] ? t - parseFloat(f["discount"].value) : t;
	// + shipping
	t = f["shipCost"] ? t + parseFloat(f["shipCost"].value) : t;
	// + tax
	t = f["taxAmount"] ? t + parseFloat(f["taxAmount"].value) : t;

	f["totalAmount"].value = Math.round(t*100)/100;
}

function forceNum(obj){
	obj.value = isNumber(obj.value) ? obj.value : 0.00;
	obj.value = Math.round(parseFloat(obj.value)*100)/100;
}

function deleteCIMItem(itemType,cid,aid){
	showItem('CIM-Delete-Over');
	showItem('CIM-Delete');		
	document.getElementById('d_cid').value = cid;
	document.getElementById('d_aid').value = aid;
	document.getElementById('d_type').value = itemType;
	
	var msg = "";
	// set the message
	if(itemType=='Shipping'){
		msg = "<h1>Are you sure you want to delete this Shipping Address</h1>";	
	}else if(itemType=='Payment'){
		msg = "<h1>Are you sure you want to delete this Payment Profile</h1>";
	}
	
	msg += '<p>Click the delete button below to delete this shipping address or cancel.</p>';
	msg += '<p>';
	msg += '	<input type="submit" name="cmdAction" value="Delete" class="formButton" />';
	msg += '	<input type="button" name="cmdAction" onclick="cancelCIMDelete();" value="Cancel" class="formButton" />';
	msg += '</p>';
	
	document.getElementById('CIM-Delete-Message').innerHTML = msg;
	
}

function cancelCIMDelete(){
	hideItem('CIM-Delete-Over');
	hideItem('CIM-Delete');	
	document.getElementById('d_cid').value = '';
	document.getElementById('d_aid').value = '';
	document.getElementById('CIM-Delete-Message').innerHTML = '';
}





	function updateCreateReturn(){
		var list = document.getElementById('ctl00_Main_ProductReturn');
		var newlist = '';
		var maxItem = parseInt(document.getElementById('itemCount').value);
		var maxMisc = parseInt(document.getElementById('miscount').value);
		var c,q,d;
		// misc items
		for(j=0;j<maxMisc;j++){
			c = document.getElementById('misc'+j);
			if(c.checked){
				newlist += (newlist == '' ? '' : '\n') + (c.value);
			}
		}
		
		// check misc other
		c = document.getElementById('miscText');
		if(c){
			if(c.value!=''){
				newlist += (newlist == '' ? '' : '\n') + (c.value);
			}
		}

		// iterate over the items and build the list
		for(j=0;j<maxItem;j++){
			c = document.getElementById('return'+j);
			if(c.checked){
				q = parseInt(document.getElementById('quantity'+j).value);
				if(q>0){
					var d = document.getElementById('desc'+j).innerHTML;
					newlist += (newlist == '' ? '' : '\n') + (d + '; Qty: ' + q);
				}
			}
		}
		


		
		list.value = newlist
	}
	
	
	function updateReturn(){
		
		// get amount ref
		var taxRate = parseFloat(document.getElementById('taxRate').value);
		// get shipping cost.
		var shippingCost = document.getElementById('CreditShipping').checked ? parseFloat(document.getElementById('shippingCost').value) : 0;

		productAmount = document.getElementById('ProductAmount');
		shippingAmount = document.getElementById('ShippingAmount');
		taxAmount = document.getElementById('TaxAmount');
		creditAmount = document.getElementById('CreditAmount');
		creditAmount.value = 0 
		totalTaxAmount = 0;
		totalProductAmount = 0;
		
		// misc credits
		miscReason = document.getElementById('_ReasonMisc');
		miscProduct = document.getElementById('_productMisc');
		miscTax = document.getElementById('_taxMisc');
		miscShipping = document.getElementById('_shippingMisc');
		
		var n = new Array(miscProduct,miscTax,miscShipping)
		for(j=0;j<n.length;j++){
			if(isNumeric(n[j].value)==false){
				n[j].value = 0.00;	
			}
		}
		
		
		var isDisabled = miscReason.value == '';
		var mf = Array(miscProduct,miscTax,miscShipping);
		for(j=0;j<mf.length;j++){
			mf[j].disabled = isDisabled;
			if(isDisabled) mf[j].value = 0;
		}
		
		// get item reference
		items = document.getElementById('returnedItems');
		items.innerHTML = '';
		var newTotal = 0;
		
		// check misc
		if(isNumeric(miscProduct.value)){
			miscTax.value = (parseFloat(miscProduct.value) * taxRate).toFixed(2);
			
			// increment new total
			newTotal += parseFloat(miscTax.value) + parseFloat(miscProduct.value);
		}
		
		if(isNumeric(miscShipping.value)){
			newTotal += parseFloat(miscShipping.value);
		}
		

		if(!isDisabled && miscReason.value!=''){
			items.innerHTML += 'Misc. Credit: ' + miscReason.value+'<br/>';
		}
		

		
		// iterate over the ids
		var qty;
		var unitcost;
		var desc;
		var ids = document.getElementsByName('orderitems');

		newTotal += shippingCost;
		
		for(j=0;j<ids.length;j++){
			var i = ids[j].value.replace(/[^\d]*/gi,'');
			if(document.getElementById('Credit'+i)){
				if(document.getElementById('Credit'+i).checked){
					qty = parseFloat(document.getElementById('qty_'+i).value);
					if(qty>0){
						unitcost = document.getElementById('UnitCost_'+i).value;
						desc = document.getElementById('desc_'+i).innerHTML;
						
						items.innerHTML += desc + ' Return Quantity: ' + qty + ' Unit Cost: ' + unitcost + '<br />';
						
						totalTaxAmount += ((parseFloat(qty) * parseFloat(unitcost)) * parseFloat(taxRate));
						totalProductAmount += (parseFloat(qty) * parseFloat(unitcost));					
						newTotal += (parseFloat(qty) * parseFloat(unitcost)) + ((parseFloat(qty) * parseFloat(unitcost)) * parseFloat(taxRate));
					}
				}
			}
		}
		
		// set ref
		shippingAmount.value = parseFloat(miscShipping.value) + parseFloat(shippingCost);
		taxAmount.value = parseFloat(miscTax.value) + parseFloat(totalTaxAmount);
		productAmount.value = parseFloat(miscProduct.value) + parseFloat(totalProductAmount);
		
		shippingAmount.value = parseFloat(shippingAmount.value).toFixed(2);
		taxAmount.value = parseFloat(taxAmount.value).toFixed(2);
		productAmount.value = parseFloat(productAmount.value).toFixed(2);
			
		creditAmount.value = newTotal.toFixed(2);
	
	}
	
function setDefault(itemType,val){
	
	if(confirm('Are you sure you want to set this as your default ' + itemType + ' method?')==false){
		return false;
	}
	
	var d = document.getElementById('Default'+itemType);
	d.value = val;

	return true;
}
