var isNN = (navigator.appName.indexOf("Netscape")!=-1);


function calc(element,v,option){
	price = element.price;
	commission = element.commission;
	percentage = element.percentage;
	sell = element.s_price;
			
	if(option == "round"){
		commission.value = v-price.value;
		percentage.value = (commission.value/price.value)*100;
	}else{
		commission.value = price.value*(v/100);
		sell.value = price.value*1+commission.value*1;
	}
}


function autoTab(input,len, e) {
	var keyCode = (isNN) ? e.which : e.keyCode; 
	var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
	if(input.value.length >= len && !containsElement(filter,keyCode)) {
	input.value = input.value.slice(0, len);
	input.form[(getIndex(input)+1) % input.form.length].focus();
}

function containsElement(arr, ele) {
	var found = false, index = 0;
	while(!found && index < arr.length)
	if(arr[index] == ele)
	found = true;
	else
	index++;
	return found;
}

function getIndex(input) {
	var index = -1, i = 0, found = false;
	while (i < input.form.length && index == -1)
	if (input.form[i] == input)index = i;
	else i++;
	return index;
	}
return true;
}


/* Check Email Validate */
function emailCheck (emailStr) {
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);
	
	if (matchArray==null) {
		alert("อีเมล์แอดเดรสของท่านไม่ถูกต้องค่ะ (กรุณาตรวนสอบ @ and .'s)");
		return false;
	}
	
	var user=matchArray[1];
	var domain=matchArray[2];
	
	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
		alert("username ประกอบไปด้วยตัวอักขระที่ไม่ถูกต้อง.");
		return false;
		   }
	}
	
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
		alert("โดเมนเนมประกอบไปด้วยตัวอักขระที่ไม่ถูกต้อง.");
		return false;
		   }
	}
	
	if (user.match(userPat)==null) {
	
	alert("username ไม่ถูกต้อง.");
	return false;
	}
	
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
	
	for (var i=1;i<=4;i++) {
		if (IPArray[i]>255) {
		alert("IP address ปลายทางไม่ถูกต้อง!");
		return false;
		   }
	}
	return true;
	}
	
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) {
		alert("โดเมนเนมของท่านไม่ถูกต้อง.");
		return false;
		   }
	}
	
	if (checkTLD && domArr[domArr.length-1].length!=2 && 
		domArr[domArr.length-1].search(knownDomsPat)==-1) {
		alert("The address must end in a well-known domain or two letter " + "country.");
		return false;
	}
	
	if (len<2) {
		alert("อีเมล์ของท่าน ดูเหมือนจะขาด hostname ค่ะ!");
		return false;
	}
	
	if(validateeven()){
	return true;
	}else{
	return false;
	}
}








function ConfirmBox(id){
	var x = confirm('You are going to delete an object that would affect other objects. Do you want to continue?');
	if(x == true) {
	document.location.href = "http://www.login.co.th/cgi-bin/sitemanager?pageid="+id+"&action=delete";
	} else {
	document.location.href = "http://www.login.co.th/cgi-bin/sitemanager?pageid="+id+"&action=view";
	}
}


function NewWindow(mypage, myname, w, h, scroll) {
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable'
	win = window.open(mypage, myname, winprops)
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
	}

function MM_displayStatusMsg(msgStr) { //v1.0
	  status=msgStr;
	  document.MM_returnValue = true;
	}
	
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_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_findObj(n, d) { //v3.0
	  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); 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];}
	}

var agt=navigator.userAgent.toLowerCase();
var is_major = parseInt(navigator.appVersion);
var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1) && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1) && (agt.indexOf('webtv')==-1));
var is_nav4 = (is_nav && (is_major == 4));
var is_nav4up = (is_nav && (is_major >= 4));

var is_nav5up = (is_nav && (is_major >= 5));
var is_ie   = (agt.indexOf("msie") != -1);
var is_ie3  = (is_ie && (is_major < 4));
var is_ie4  = (is_ie && (is_major == 4) && (agt.indexOf("msie 4.")!=-1));
var is_ie5up  = (is_ie  && !is_ie3 && !is_ie4 && agt.indexOf("opera") == -1);

var is_compatible_browser = (is_ie5up || is_nav5up);



function OnChangeCategoryCPU(catorder, defitem, defcolor)
{
  OnChangeCategory(catorder, defitem, defcolor);  
  
  arrCPUs = eval ("arrItems" + catorder);
  catCPUs = eval ("document.forms[0].Cat" + catorder);
  if (catCPUs)
    selCPU = catCPUs.selectedIndex;
  else
    selCPU = defitem;
  mbidx = arrCPUs[selCPU][3];

  itemid = link = '';  
  document.forms[0].MBCat.options[0].text = arrMBoards[mbidx][0];
  
  if ( (itemid = arrMBoards[mbidx][1]) != '' ) {
    link = 'details_pages/details_pages.asp?catname=Motherboard&itemlist='+itemid;
    document.images['detailsimage'].src = imageDetailson.src;
  } else {
    link = ''; 
    document.images['detailsimage'].src = imageDetailsoff.src;
  }      
  
  for (idx=0; idx < document.links.length; idx++) {
     target = document.links[idx].target + '';     
     if (target.indexOf('VIEW_DETAILS_MOTHERBOARD') != -1) {
        document.links[idx].href = link;
        break;
     }     
  }
}
  
function OnChangeCategory(catorder, defitem, defcolor)
{
  category = eval ("document.forms[0].Cat" + catorder);
  var firsttime = true;
  if (defitem == -1) {
    firsttime = false;
    defitem = category.selectedIndex;
  }
  color = eval ("document.forms[0].MenuColor" + catorder);
 
  arrItems = eval ("arrItems" + catorder);
  var desc = arrItems[defitem][0];

  if (desc.indexOf ("- COLOR") == -1) {      
    curprice = arrItems[defitem][1];
    updateMenu (category, defitem, arrItems);  
    if (color)
      if (is_compatible_browser) 
        color.style.visibility = 'hidden';
      else { 
        for (i = color.length - 1; i >= 1; i--)
          color.options[i] = null;
        color.options[0].text = '';
      }
  }
  else {
    if (defcolor == -1)
	defcolor = 0;

    arrColors = eval ("arrItems" + catorder + "_" + defitem);
    curprice = defcolorprice = arrColors[defcolor][1];
    arrItems[defitem][1] = defcolorprice;
    updateMenu (category, defitem, arrItems);
    arrItems[defitem][1] = -1;

    updateMenu (color, defcolor, arrColors);
    if (color && is_compatible_browser) 
      color.style.visibility = 'visible';
  }

  if (firsttime)
    g_dTotal = g_dTotal + curprice;
  else {
    g_dTotal = g_dTotal - arrPrices[catorder] + curprice;
    UpdatePrice (g_dTotal);
  }
  arrPrices[catorder] = curprice;
}

function OnChangeColor(catorder)
{
    category = eval ("document.forms[0].Cat" + catorder);
    defitem = category.selectedIndex;
    color = eval ("document.forms[0].MenuColor" + catorder);
    defcolor = color.selectedIndex;

    arrItems = eval ("arrItems" + catorder);
    arrColors = eval ("arrItems" + catorder + "_" + defitem);

    curprice = defcolorprice = arrColors[defcolor][1];
    arrItems[defitem][1] = defcolorprice;
    updateMenu (category, defitem, arrItems);
    arrItems[defitem][1] = -1;

    updateMenu (color, defcolor, arrColors);

    g_dTotal = g_dTotal - arrPrices[catorder] + curprice;
    UpdatePrice (g_dTotal);
    arrPrices[catorder] = curprice;
}

function updateMenu (menu, defaultindex, arrItems)
{
    if (!menu)
      return;

    defaultprice = arrItems[defaultindex][1];

    for (i = 0; i < arrItems.length; i++) {
      var desc = arrItems[i][0];
      if (desc.indexOf ("- COLOR") == -1 && i != defaultindex) {
	  var pricediff = arrItems[i][1] - defaultprice;
        if (pricediff > 0)
          sufix = " [+" + pricediff + "]";
        else
	    sufix = " [" + pricediff + "]";
	  desc += sufix;
      }

	//if (menu.options[i] == null)
	  menu.options[i] = new Option(desc,arrItems[i][2]);
      //else
	//  menu.options[i].text = desc;
    }

    for (i = menu.length - 1; i >= arrItems.length; i--)
      menu.options[i] = null;

    menu.selectedIndex = defaultindex;
} 

function NewWindow(url, myname, w, h, scroll)
{
   var winl = (screen.width - w) / 2;
   var wint = (screen.height - h) / 2;
   winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable=1';
   win = window.open(url, myname, winprops);
   if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
} 

function ModifyHREF(sele, arrItems) {
   if (arrItems && arrItems[sele.selectedIndex] && arrItems[sele.selectedIndex][2])  
      return '#' + arrItems[sele.selectedIndex][2];
   else return '';
}

function ChangeinnerHTML(layerid, htmlcode) {
    var statement = '';
    
	
    if (document.all) 
	  statement += "document.all['" + layerid + "'].innerHTML = '" + htmlcode + "';";	     
    else if (document.getElementById)           
	  statement += "document.getElementById('" + layerid + "').innerHTML = '" + htmlcode + "';"; 
    
    eval(statement);    
}

function ValidNumber (str)
{
   return ! isNaN (str * 1);
}

function AddToCart (theForm, targetURL)
{
   ValidateAndSubmit(theForm, targetURL); 
}

function SaveQuote (theForm, targetURL)
{
  
    
  var emailaddr = prompt('Enter your e-mail address:', lastemailaddr);
  if (emailaddr != null && emailaddr != "")
      ValidateAndSubmit(theForm, targetURL + "?SaveQuote=" + emailaddr + '');    
}

function RetrieveQuote (theForm, targetURL)
{
  var emailquoteid = prompt('Enter quote ID:', lastquoteid);
  if (emailquoteid != null && emailquoteid != "") {
    lastquoteid = emailquoteid;
    var dash = emailquoteid.lastIndexOf ("-");
    if (dash == -1)
      alert ('Invalid quote ID.');
    else {
      var emailaddr = emailquoteid.substring (0, dash);
      var quoteid = emailquoteid.substring (dash + 1, 100); 
      if (! ValidNumber (quoteid))
        alert ('Invalid quote ID.');
      else 
       RedirectAndSubmit(theForm, targetURL + "?RetrieveQuote=" + emailquoteid);
    }
  }
}

function ValidateAndSubmit(theForm, targetURL)
{
   if (ValidateSystem())
	RedirectAndSubmit(theForm, targetURL);
   else {
	ShowMessagePopup();
   }  
}

function RedirectAndSubmit(theForm, targetURL)
{
  theForm.action = targetURL;
  theForm.submit();
  return true;
}

function RoundPrice(nValue)
{
    sign = (nValue >= 0) ? 1 : -1;

    nValue = Math.abs (nValue); 
	var nTempValue = nValue*100;
	nTempValue = Math.round(nTempValue);
	var nRemainder = nTempValue % 100;
	nTempValue -= nRemainder;		// get rid of decimals..

	nTempValue /= 100;

	var strValue = nTempValue.toString();
	var strDecimals = nRemainder.toString();
	if (strDecimals.length < 2)
		strDecimals = "0" + strDecimals;

	var strResult = strValue + "." + strDecimals;
	return strResult * sign;
}

/********************* Validate systems issues.... *********************/

var msgList;
var bboard="";
var bprocessor="";
var has_scsi_controller=false;

function msgPrint(txt)
{	msgList[msgList.length]=txt;
}

function elemMax()
{	var v=arrCat.length;
	return v;
}

function elemItem(i)
{
	var order=arrCat[i][0];
	var idx='document.forms[0].Cat'+order+'.selectedIndex';
	var v;
	var catName=arrCat[i][1];
	if (catName.toUpperCase().indexOf("PROCESSOR")==0)
	{
		bprocessor=eval("arrItems"+order+"["+idx+"][0]");
		var processorb=eval("arrItems"+order+"["+idx+"][3]");
		bboard=arrMBoards[processorb][0];
	}
// This try statement doesn't work on NN4 browser
//	try
//	{
		idx=eval(idx);
//	} catch (e)
//	{	idx=arrCat[i][2];
//	}
	v=eval('arrItems'+order+'[idx][0]').toUpperCase();
	if (v=='(NONE)')
	{
		v='';
	}
	return v;
}

function CheckForNeedSCSI()
{
	has_scsi_controller=false;
	var found_any_scsi=false;
	var is_onboard=false;
	var n=elemMax();
	for (var i=0;i<n;i++)
	{
		var szDescription = elemItem(i).toUpperCase();
		if (szDescription.indexOf ("SCSI") != -1)
		{ 
			if ( (szDescription.indexOf("CONTROLLER")!=-1)||(szDescription.indexOf("ONBOARD")!=-1) )
			{
				has_scsi_controller=true;
				is_onboard |= ( (szDescription.indexOf("ON-BOARD")!=-1) || (szDescription.indexOf("ONBOARD")!=-1) );
			} else
			{
				found_any_scsi=true;
			}
		} 
	}
	if (bboard.indexOf("ONBOARD")!=-1)
	{
		has_scsi_controller=true;
		is_onboard=true;
	}

	if ( (has_scsi_controller) && (!found_any_scsi) && (!is_onboard))
	{
		alert("This configuration contains a SCSI controller, but no SCSI devices.\r\n Please verify a SCSI controller is necessary before adding to cart.");
	}
	if ( (!has_scsi_controller) && (found_any_scsi) )
	{
		msgPrint("This configuration contains one or more SCSI devices, but no SCSI controller.\r\n Please select a SCSI controller before adding to cart.");
	}
}

function CheckForBayUsed()
{
	var n=elemMax();
	var nMaxBays = 3;
	var nBays = 0;
	for (var i=0;i<n;i++)
	{
		var catOrder = arrCat[i][0];
		var szDescription = elemItem(i);
		var szCategory = arrCat[i][1].toUpperCase();
		if (szDescription.length>0)
		{
			if (szCategory.indexOf("CASE")!=-1) {
					if (szDescription.indexOf("FULL-TOWER")!=-1)
						nMaxBays = 4;
					else
					if (szDescription.indexOf("SC5000")!=-1)
						nMaxBays = 5;
					else
						nMaxBays = 3;
			}
			else if ((szCategory.indexOf("CD-ROM")!=-1)||(szCategory.indexOf("CD-RW")!=-1)) {
				// CD-ROM occupies 1 bay
					nBays ++;
			} else if (szCategory.indexOf("DVD-ROM")!=-1) {
				// DVD also
					nBays ++;
			} else if (szCategory.indexOf("STORAGE")!=-1) {
				// Storage devices (non external)
					if (szDescription.indexOf("EXTERNAL")==-1)
					{	nBays ++;
						if (szDescription.indexOf("IOMEGA")!=-1)
						{
							if ((szDescription.indexOf("100")!=-1)||(szDescription.indexOf("250")!=-1))
								nBays--;
						} else
						if (szDescription.indexOf("LS-120")!=-1)
							nBays--;
					}
			} else if (szCategory.indexOf("DIGITAL VIDEO")!=-1) {
				// Digital video which mentions "bay"
					if (szDescription.indexOf("BAY")!=-1)
					{	nBays ++;
					}
			} else if (szCategory.indexOf("SOUND CARD")!=-1) {
					if (szDescription.indexOf("PLATINUM")!=-1)
					{	nBays++;
					}
			}
		}
	}
	if (nMaxBays<nBays)
		msgPrint("This configuration has "+nMaxBays+" total bays and "+nBays+" devices selected.\r\n Please drop the necessary number of devices before adding to cart.");
}

function CheckIDE()
{
	var n=elemMax();
	var nIDE = 4;
	var nUsed = 0;
	for (var i=0;i<n;i++)
	{
		var catOrder = arrCat[i][0];
		var szDescription = elemItem(i);
		var szCategory = arrCat[i][1].toUpperCase();
		if (szDescription.length>0)
		{
			if (szCategory.indexOf("DVD-ROM")!=-1)
			{	if (szDescription.indexOf("SCSI")==-1)
					nUsed++;
			} else
			if ( (szCategory.indexOf("CD-ROM")!=-1)||(szCategory.indexOf("CD-RW")!=-1) )
			{	if (szDescription.indexOf("SCSI")==-1)
					nUsed++;
			} else
			if (szCategory.indexOf("SCSI/IDE")!=-1)
			{	if ((szDescription.indexOf("IDE")!=-1)||(szDescription.indexOf("ATA")!=-1))
					nIDE+=4;
			} else
			if ((szCategory.indexOf("STORAGE")!=-1)&&(szDescription.indexOf("SCSI")==-1))
			{
				if (szDescription.indexOf("EXTERNAL")==-1) 
					nUsed++;
			} else
			if ( (szCategory.indexOf("HARD")!=-1) && (szCategory.indexOf("DRIVE")!=-1) )
			{
				if (szDescription.indexOf("SCSI")==-1)
					nUsed++;
			}
		}
	}
	if (nIDE<nUsed)
		msgPrint("This configuration has "+nIDE+" channels and "+nUsed+" IDE devices\r\n Please select an IDE controller or remove an IDE device before adding to cart");
}

function CheckForPCIUsed()
{
	var n=elemMax();
	var nPCISlots = 5; 
	var nInUsePCI = 0;
	for (var i=0;i<n;i++)
	{
		var catOrder = arrCat[i][0];
		var szDescription = elemItem(i);
		var szCategory = arrCat[i][1].toUpperCase();
		if (szDescription.length!=0)
		{
			if (szCategory.indexOf("SCSI/IDE")!=-1)  // IDE/SCSI Controller takes 1 if it's not onboard
			{	if ((szDescription.indexOf("ON-BOARD")==-1) && (szDescription.indexOf("ONBOARD")==-1))
					nInUsePCI ++;
			} else
			if (szCategory.indexOf("DVD-ROM")!=-1)  // Digital video, HARDWARE-MPEG
			{	if (szDescription.indexOf("HARDWARE")!=-1)
					nInUsePCI ++;
			} else
			if (szCategory.indexOf("MODEM")!=-1) // Modems take 1
				nInUsePCI ++;
			else				
			if (szCategory.indexOf("ETHERNET")!=-1) // LAN Adaptor
			 	nInUsePCI ++;
			else
			if (szCategory.indexOf("SOUND")!=-1) // Soundcard
				nInUsePCI ++;
			else
			if (szCategory.indexOf("DIGITAL VIDEO")!=-1) // DV kit
				nInUsePCI ++;
		}
	}
	if (bboard.indexOf("STL2")!=-1)
	{	nPCISlots = 6;	// El Motherboard de Intel de 6 PCI Slots
	} else
	{	var pciPos=bboard.indexOf("PCI");	
		if (pciPos>=0)
			nPCISlots=eval(bboard.charAt(pciPos-1));
	}
	if (nInUsePCI>nPCISlots)
		msgPrint("This configuration has "+nPCISlots+" total PCI slots and "+nInUsePCI+" PCI devices selected.\r\n Please drop the necessary number of PCI devices before adding to cart.");
}

function CheckMemories()
{
	var n=elemMax();
	var szMemory="";
	var szProcessor="";
	var szOS="";
	var bUseNIC=false;
	var bNICOnBoard=false;
	for (var i=0;i<n;i++)
	{
		var catOrder = arrCat[i][0];
		var szDescription = elemItem(i);
		var szCategory = arrCat[i][1].toUpperCase();
		switch (szCategory)
		{
			case "MEMORY":
			{	szMemory=szDescription;
				break;
			}
			case "OPERATING SYSTEM":
			{
				szOS=szDescription;
				break;
			}
			case "ETHERNET NIC":
			{
				bUseNIC=(szDescription.length>0);
				break;
			}
		}
	}
	szProcessor=bprocessor.toUpperCase();
	bNICOnBoard=(bboard.indexOf("840")!=-1) || (bboard.indexOf("NIC")!=-1);
	if (bUseNIC && bNICOnBoard)
		msgPrint("The "+bboard+"motherboard in this configuration provides an onboard Network Interface Card.\r\n Please drop the selected Network Interface Card before adding to cart");
	var prError=0;
	if ( ((szProcessor.indexOf("THUNDERBIRD")!=-1) || (szProcessor.indexOf("DURON")!=-1)) && (szMemory.indexOf("RDRAM")!=-1) )
		prError ++;
	if ( (szProcessor.indexOf("PENTIUM")!=-1) && (szMemory.indexOf("VIRTUAL CHANNEL")!=-1) )
		prError ++;
	if ( (szProcessor.indexOf("PENTIUM")!=-1) && (szProcessor.indexOf("III")!=-1) && (szMemory.indexOf("RDRAM")!=-1) )
		prError ++;
	if (bboard.indexOf("840")!=-1)
	{
		if (szMemory.indexOf("RDRAM")==-1)
		{	msgPrint("The "+bboard+" motherboard in this configuration is only compatible with RDRAM.\r\n Please select RDRAM memory before adding to cart.");
		}	
	}
	if (szProcessor.indexOf("PENTIUM")!=-1)
	{
		if (szProcessor.indexOf("4")!=-1)
		{
			if ( szMemory.indexOf("SDRAM")!=-1)
				prError++;
		}
	}
	if ( (szOS.indexOf("MILLENNIUM")!=-1) && (szMemory.indexOf("512")!=-1) && (szMemory.indexOf("RDRAM")!=-1) )
	{
		msgPrint("Microsoft Windows Millennium may not experience optimal performance with 512MB of RAM.\r\n Please select less than 512MB of RAM before adding to cart.");
	}
	if (prError>0)
		msgPrint("The "+szProcessor+" processor is not compatible with "+szMemory+" memory.\r\n Please select another type of memory before adding to cart.");
}

function CheckRules()
{
	var n=elemMax();
	var nCDs = 0;
	var bHasController = false;
	var bHasSoftwareDVD = false;
	var bUse3DLabs = false;
	var bRAID = false;
	var bUseNIC = false;
	var isP4 = false;
	var SCSIP3 = false;
	for (var i=0;i<n;i++)
	{
		var catOrder = arrCat[i][0];
		var szDescription = elemItem(i);
		var szCategory = arrCat[i][1].toUpperCase();
		var xchgd=false;
		if (szDescription.length>0)
		{
			if (szDescription.indexOf("PENTIUM III ONLY")!=-1)
				SCSIP3=true;
			if (szCategory.indexOf("ETHERNET")!=-1)
				bUseNIC = true;

			isP4 |= ((szDescription.indexOf("PENTIUM")!=-1) && (szDescription.indexOf("4 PROCESSOR")!=-1));

			if (szCategory.indexOf("DVD-ROM")!=-1)
			{	if (szDescription.indexOf("SCSI")==-1)
				{
					nCDs++;
					xchgd=true;
				}
				if (szDescription.indexOf("HARDWARE")==-1)
				{	bHasSoftwareDVD = true;
					xchgd=true;
				}
			} else
			if ((szCategory.indexOf("CD-ROM")!=-1)||(szCategory.indexOf("CD-RW")!=-1))
			{	if (szDescription.indexOf("SCSI")==-1)
				{	nCDs++;
					xchgd=true;
				}
			} else
			if (szCategory.indexOf("SCSI/IDE")!=-1)
			{	if ((szDescription.indexOf("IDE")!=-1)||(szDescription.indexOf("ATA")!=-1))
				{	bHasController=true;
					xchgd=true;
				} 
			} else
			if (szCategory.indexOf("STORAGE")!=-1)
			{
				if ((szDescription.indexOf("IDE")!=-1)&&(szDescription.indexOf("ZIP")==-1))
				{	nCDs++;
					xchgd=true;
				}
			} else
			if (szCategory.indexOf("VIDEO")!=-1)
			{
				if ((szDescription.indexOf("3DLABS")!=-1)&&(szDescription.indexOf("420")!=-1))
				{	bUse3DLabs = true;
					xchgd=true;
				}
			} else
			if (szCategory.indexOf("RAID CONFIGURATION")!=-1)
			{	if (szDescription.indexOf("U3-1L")==-1)
				{	bRAID=true;
				}
			} 
		}
		//if (xchgd)
		//	alert("nCDs="+nCDs+"\nbHasController="+bHasController+"\nszCategory="+szCategory+"\nszDescription="+szDescription);
	}
	
//	if ((document.forms[0].sSyscode.value.indexOf("ALPHA")!=-1) && bRAID && bUseNIC)
//		msgPrint("This RAID cannot be used with a desktop adapter");

	if (SCSIP3 && isP4)
		msgPrint("The SCSI/RAID controler selected, will not work with your current configuration.\r\n Please select another SCSI/RAID controller.");

	if (bUse3DLabs && bHasSoftwareDVD)
		msgPrint("The video card selected requires a DVD-ROM w/Hardware MPEG-2 Decoder.\r\n Please select a DVD-ROM w/Hardware MPEG-2 Decoder before adding to cart.");
	if ( (nCDs>=3) && (!bHasController) )
		msgPrint("This configuration has "+nCDs+" secondary IDE devices.\r\nPlease select an IDE controller or remove a secondary IDE device before adding to cart");
}

function CheckSCSIRAID()
{
	var n = elemMax();
	var bRAID = false;
	var bRAIDController = false;
	var bRAIDCapacity = 0;
	var bRAIDUsed = 0;
	var Hardisks = new Array();

	for (var i=0;i<n;i++)
	{
		var catOrder = arrCat[i][0];
		var szDescription = elemItem(i).toUpperCase();
		var szCategory = arrCat[i][1].toUpperCase();

		if (szDescription.length==0)
			continue;
		if ( (szCategory.indexOf("RAID")!=-1) && (szCategory.indexOf("CONFIGURATION")!=-1) && (szDescription.length>0) )
		{	bRAID=true;
			var pPos=szDescription.indexOf("W/");
			if (pPos>=0)
			{
				var bSubStr=szDescription.substr(pPos,bboard.length);
				var space=bSubStr.indexOf("SCSI");
				bSubStr=bSubStr.substr(2,space-2);
				bRAIDCapacity=eval(bSubStr);
			}
		} else
		if ((szCategory.indexOf("HARD")!=-1) && (szCategory.indexOf("DRIVE")!=-1))
		{
			if (szDescription.indexOf("SCSI")!=-1)
			{
				bRAIDUsed ++;
				Hardisks[Hardisks.length]=szDescription;
			}
		} 
		if ((szDescription.indexOf("RAID")!=-1) && ((szDescription.indexOf("CONTROLLER")!=-1) || (szDescription.indexOf("SERVER")!=-1)) )
		{
			bRAIDController=true;
		}
	}
	//alert("bRAID = "+bRAID+"\nbRAIDController="+bRAIDController+"\nbRAIDCapacity="+bRAIDCapacity+"\nbRAIDUsed="+bRAIDUsed);
	if (!bRAID)
	{
		if (bRAIDController)
			msgPrint("This configuration contains a RAID controller, but no RAID configuration has been selected.\r\n Please select a RAID configuration before adding to cart.");
		return;
	}
	if (bRAIDController) 
	{
		if (bRAIDCapacity<bRAIDUsed) 
			msgPrint("Please select a RAID configuration and a matching number of hard drives before adding to cart.");
		if (bRAIDUsed<2)
			msgPrint("This configuration contains a RAID controller and only one SCSI hard drive.\r\n Please select more than one SCSI hard drive before adding to cart.");
		var bDifferent=false;
		var first=Hardisks[0];
		for (var i=1;i<Hardisks.length;i++)
		{
			if (first!=Hardisks[i])
			{
				bDifferent=true;
				break;
			}
		}
		if (bDifferent)
			msgPrint("This configuration contains a RAID controller and hard drives of different sizes.\r\n Please select hard drives with identical sizes before adding to cart.");
	} else
		msgPrint("This configuration contains a RAID configuration, but no RAID controller.\r\n Please select a RAID controller before adding to cart.");
}


/*
function ShowMessagePopup()
{
	var Messages=window.open("","Messages","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=400,height=300");
	var htmlcode="<HTML><HEAD><TITLE>Messages</TITLE></HEAD><BODY>"+
	             "<TABLE cellSpacing=0 cellPadding=0 width='100%' border=1><TR><TD bgcolor=silver><h4>Problems list</h4></TD></TR>";
	for (var i=0;i<msgList.length;i++)
	{
		htmlcode +="<TR><TD"; 
		if (i%2==1)
			htmlcode += " bgcolor=f0f0f0";
		htmlcode += ">"+msgList[i]+"</TD></TR>\n";
	}
	htmlcode+="</TABLE></HTML><br><a href='javascript:self.close();'>Close this window</a>";
	Messages.document.write(htmlcode);
}
*/

function ShowMessagePopup()
{
	var msg="Configuration Assistance Activated\r\n";
	var bullet="- ";
	for (i=0;i<msgList.length;i++)
		msg += "\r\n"+bullet+msgList[i];
	alert(msg);
}

function CheckHotBays()
{
	var n = elemMax();
	var nHotBays = 0;
	var nHotBaysUsed = 0;
	for (var i=0;i<n;i++)
	{
		var catOrder = arrCat[i][0];
		var szDescription = elemItem(i).toUpperCase();
		var szCategory = arrCat[i][1].toUpperCase();
		if ( (szCategory.indexOf("CASE")!=-1) || (szCategory.indexOf("CHASSIS")!=-1) )
		{
			var pos=szDescription.indexOf("HOT SWAP BAY");
			if (pos!=-1) // Nothing to do if there isn't hot bays in the description
			{
				var szSub=szDescription.substr(0,pos);
				pos=szSub.length;
				while ((pos>0) && (szSub.substr(pos,1)!="/"))
					pos--;
				nHotBays=eval(szSub.substr(pos+1,szSub.length));
			} else
			if (szDescription.indexOf("SRMK2S ")!=-1)	// Intel chassis has four hotbays
			{
				nHotBays=4;
			} else
				nHotBays=1000; // Case does not have hot bays, so any SCSI hard drives will fit inside.
		}
		if ( (szCategory.indexOf("HARD")!=-1) && ((szCategory.indexOf("DISK")!=-1) || (szCategory.indexOf("DRIVE")!=-1)) )
		{
			if (szDescription.indexOf("SCSI")!=-1)
				nHotBaysUsed++;
		}
	}
	if (nHotBays<nHotBaysUsed)
		msgPrint("This configuration has "+nHotBays+" total hard drive bays and "+nHotBaysUsed+" hard drives selected.\r\n Please drop the necessary number of hard drives before adding to cart.");
}

function ValidateSystem()
{
	msgList=new Array();
	bboard="";
	CheckForPCIUsed();
	CheckForBayUsed();
	CheckMemories();
	CheckForNeedSCSI();
	CheckIDE();
	CheckRules();
	CheckSCSIRAID();
	CheckHotBays();
	return (msgList.length==0);
}








// ******************************************************************************************************BEGIN CALENDAR

var weekend = [0,6];
var weekendColor = "#e0e0e0";
var fontface = "Verdana";
var fontsize = 2;

var gNow = new Date();
var ggWinCal;
isNav = (navigator.appName.indexOf("Netscape") != -1) ? true : false;
isIE = (navigator.appName.indexOf("Microsoft") != -1) ? true : false;

Calendar.Months = ["มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน","กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"];

// Non-Leap year Month days..
Calendar.DOMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// Leap year Month days..
Calendar.lDOMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

function Calendar(p_item, p_WinCal, p_month, p_year, p_format) {
	if ((p_month == null) && (p_year == null))	return;

	if (p_WinCal == null)
		this.gWinCal = ggWinCal;
	else
		this.gWinCal = p_WinCal;
	
	if (p_month == null) {
		this.gMonthName = null;
		this.gMonth = null;
		this.gYearly = true;
	} else {
		this.gMonthName = Calendar.get_month(p_month);
		this.gMonth = new Number(p_month);
		this.gYearly = false;
	}

	this.gYear = p_year;
	this.gFormat = p_format;
	this.gBGColor = "white";
	this.gFGColor = "black";
	this.gTextColor = "black";
	this.gHeaderColor = "black";
	this.gReturnItem = p_item;
}

Calendar.get_month = Calendar_get_month;
Calendar.get_daysofmonth = Calendar_get_daysofmonth;
Calendar.calc_month_year = Calendar_calc_month_year;
Calendar.print = Calendar_print;

function Calendar_get_month(monthNo) {
	return Calendar.Months[monthNo];
}

function Calendar_get_daysofmonth(monthNo, p_year) {
	/* 
	Check for leap year ..
	1.Years evenly divisible by four are normally leap years, except for... 
	2.Years also evenly divisible by 100 are not leap years, except for... 
	3.Years also evenly divisible by 400 are leap years. 
	*/
	if ((p_year % 4) == 0) {
		if ((p_year % 100) == 0 && (p_year % 400) != 0)
			return Calendar.DOMonth[monthNo];
	
		return Calendar.lDOMonth[monthNo];
	} else
		return Calendar.DOMonth[monthNo];
}

function Calendar_calc_month_year(p_Month, p_Year, incr) {
	/* 
	Will return an 1-D array with 1st element being the calculated month 
	and second being the calculated year 
	after applying the month increment/decrement as specified by 'incr' parameter.
	'incr' will normally have 1/-1 to navigate thru the months.
	*/
	var ret_arr = new Array();
	
	if (incr == -1) {
		// B A C K W A R D
		if (p_Month == 0) {
			ret_arr[0] = 11;
			ret_arr[1] = parseInt(p_Year) - 1;
		}
		else {
			ret_arr[0] = parseInt(p_Month) - 1;
			ret_arr[1] = parseInt(p_Year);
		}
	} else if (incr == 1) {
		// F O R W A R D
		if (p_Month == 11) {
			ret_arr[0] = 0;
			ret_arr[1] = parseInt(p_Year) + 1;
		}
		else {
			ret_arr[0] = parseInt(p_Month) + 1;
			ret_arr[1] = parseInt(p_Year);
		}
	}
	
	return ret_arr;
}

function Calendar_print() {
	ggWinCal.print();
}

function Calendar_calc_month_year(p_Month, p_Year, incr) {
	/* 
	Will return an 1-D array with 1st element being the calculated month 
	and second being the calculated year 
	after applying the month increment/decrement as specified by 'incr' parameter.
	'incr' will normally have 1/-1 to navigate thru the months.
	*/
	var ret_arr = new Array();
	
	if (incr == -1) {
		// B A C K W A R D
		if (p_Month == 0) {
			ret_arr[0] = 11;
			ret_arr[1] = parseInt(p_Year) - 1;
		}
		else {
			ret_arr[0] = parseInt(p_Month) - 1;
			ret_arr[1] = parseInt(p_Year);
		}
	} else if (incr == 1) {
		// F O R W A R D
		if (p_Month == 11) {
			ret_arr[0] = 0;
			ret_arr[1] = parseInt(p_Year) + 1;
		}
		else {
			ret_arr[0] = parseInt(p_Month) + 1;
			ret_arr[1] = parseInt(p_Year);
		}
	}
	
	return ret_arr;
}

// This is for compatibility with Navigator 3, we have to create and discard one object before the prototype object exists.
new Calendar();

Calendar.prototype.getMonthlyCalendarCode = function() {
	var vCode = "";
	var vHeader_Code = "";
	var vData_Code = "";
	
	// Begin Table Drawing code here..
	vCode = vCode + "<TABLE BORDER=1 BGCOLOR=\"" + this.gBGColor + "\">";
	
	vHeader_Code = this.cal_header();
	vData_Code = this.cal_data();
	vCode = vCode + vHeader_Code + vData_Code;
	
	vCode = vCode + "</TABLE>";
	
	return vCode;
}

Calendar.prototype.show = function() {
	var vCode = "";
	
	this.gWinCal.document.open();

	// Setup the page...
	this.wwrite("<html>");
	this.wwrite("<head><title>Calendar</title>");
	this.wwrite("</head>");

	this.wwrite("<body " + 
		"link=\"" + this.gLinkColor + "\" " + 
		"vlink=\"" + this.gLinkColor + "\" " +
		"alink=\"" + this.gLinkColor + "\" " +
		"text=\"" + this.gTextColor + "\">");
	this.wwriteA("<FONT FACE='" + fontface + "' SIZE=2><B>");
	this.wwriteA(this.gMonthName + " " + this.gYear);
	this.wwriteA("</B><BR>");

	// Show navigation buttons
	var prevMMYYYY = Calendar.calc_month_year(this.gMonth, this.gYear, -1);
	var prevMM = prevMMYYYY[0];
	var prevYYYY = prevMMYYYY[1];

	var nextMMYYYY = Calendar.calc_month_year(this.gMonth, this.gYear, 1);
	var nextMM = nextMMYYYY[0];
	var nextYYYY = nextMMYYYY[1];
	
	this.wwrite("<TABLE WIDTH='100%' BORDER=1 CELLSPACING=0 CELLPADDING=0 BGCOLOR='#e0e0e0'><TR><TD ALIGN=center>");
	this.wwrite("[<A HREF=\"" +
		"javascript:window.opener.Build(" + 
		"'" + this.gReturnItem + "', '" + this.gMonth + "', '" + (parseInt(this.gYear)-1) + "', '" + this.gFormat + "'" +
		");" +
		"\"><<<\/A>]</TD><TD ALIGN=center>");
	this.wwrite("[<A HREF=\"" +
		"javascript:window.opener.Build(" + 
		"'" + this.gReturnItem + "', '" + prevMM + "', '" + prevYYYY + "', '" + this.gFormat + "'" +
		");" +
		"\"><<\/A>]</TD><TD ALIGN=center>");
	this.wwrite("[<A HREF=\"javascript:window.print();\">Print</A>]</TD><TD ALIGN=center>");
	this.wwrite("[<A HREF=\"" +
		"javascript:window.opener.Build(" + 
		"'" + this.gReturnItem + "', '" + nextMM + "', '" + nextYYYY + "', '" + this.gFormat + "'" +
		");" +
		"\">><\/A>]</TD><TD ALIGN=center>");
	this.wwrite("[<A HREF=\"" +
		"javascript:window.opener.Build(" + 
		"'" + this.gReturnItem + "', '" + this.gMonth + "', '" + (parseInt(this.gYear)+1) + "', '" + this.gFormat + "'" +
		");" +
		"\">>><\/A>]</TD></TR></TABLE><BR>");

	// Get the complete calendar code for the month..
	vCode = this.getMonthlyCalendarCode();
	this.wwrite(vCode);

	this.wwrite("</font></body></html>");
	this.gWinCal.document.close();
}

Calendar.prototype.showY = function() {
	var vCode = "";
	var i;
	var vr, vc, vx, vy;		// Row, Column, X-coord, Y-coord
	var vxf = 285;			// X-Factor
	var vyf = 200;			// Y-Factor
	var vxm = 10;			// X-margin
	var vym;				// Y-margin
	if (isIE)	vym = 75;
	else if (isNav)	vym = 25;
	
	this.gWinCal.document.open();

	this.wwrite("<html>");
	this.wwrite("<head><title>Calendar</title>");
	this.wwrite("<style type='text/css'>\n<!--");
	for (i=0; i<12; i++) {
		vc = i % 3;
		if (i>=0 && i<= 2)	vr = 0;
		if (i>=3 && i<= 5)	vr = 1;
		if (i>=6 && i<= 8)	vr = 2;
		if (i>=9 && i<= 11)	vr = 3;
		
		vx = parseInt(vxf * vc) + vxm;
		vy = parseInt(vyf * vr) + vym;

		this.wwrite(".lclass" + i + " {position:absolute;top:" + vy + ";left:" + vx + ";}");
	}
	this.wwrite("-->\n</style>");
	this.wwrite("</head>");

	this.wwrite("<body " + 
		"link=\"" + this.gLinkColor + "\" " + 
		"vlink=\"" + this.gLinkColor + "\" " +
		"alink=\"" + this.gLinkColor + "\" " +
		"text=\"" + this.gTextColor + "\">");
	this.wwrite("<FONT FACE='" + fontface + "' SIZE=2><B>");
	this.wwrite("Year : " + this.gYear);
	this.wwrite("</B><BR>");

	// Show navigation buttons
	var prevYYYY = parseInt(this.gYear) - 1;
	var nextYYYY = parseInt(this.gYear) + 1;
	
	this.wwrite("<TABLE WIDTH='100%' BORDER=1 CELLSPACING=0 CELLPADDING=0 BGCOLOR='#e0e0e0'><TR><TD ALIGN=center>");
	this.wwrite("[<A HREF=\"" +
		"javascript:window.opener.Build(" + 
		"'" + this.gReturnItem + "', null, '" + prevYYYY + "', '" + this.gFormat + "'" +
		");" +
		"\" alt='Prev Year'><<<\/A>]</TD><TD ALIGN=center>");
	this.wwrite("[<A HREF=\"javascript:window.print();\">Print</A>]</TD><TD ALIGN=center>");
	this.wwrite("[<A HREF=\"" +
		"javascript:window.opener.Build(" + 
		"'" + this.gReturnItem + "', null, '" + nextYYYY + "', '" + this.gFormat + "'" +
		");" +
		"\">>><\/A>]</TD></TR></TABLE><BR>");

	// Get the complete calendar code for each month..
	var j;
	for (i=11; i>=0; i--) {
		if (isIE)
			this.wwrite("<DIV ID=\"layer" + i + "\" CLASS=\"lclass" + i + "\">");
		else if (isNav)
			this.wwrite("<LAYER ID=\"layer" + i + "\" CLASS=\"lclass" + i + "\">");

		this.gMonth = i;
		this.gMonthName = Calendar.get_month(this.gMonth);
		vCode = this.getMonthlyCalendarCode();
		this.wwrite(this.gMonthName + "/" + this.gYear + "<BR>");
		this.wwrite(vCode);

		if (isIE)
			this.wwrite("</DIV>");
		else if (isNav)
			this.wwrite("</LAYER>");
	}

	this.wwrite("</font><BR></body></html>");
	this.gWinCal.document.close();
}

Calendar.prototype.wwrite = function(wtext) {
	this.gWinCal.document.writeln(wtext);
}

Calendar.prototype.wwriteA = function(wtext) {
	this.gWinCal.document.write(wtext);
}

Calendar.prototype.cal_header = function() {
	var vCode = "";
	
	vCode = vCode + "<TR>";
	vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Sun</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Mon</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Tue</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Wed</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Thu</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='14%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Fri</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='16%'><FONT SIZE='2' FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Sat</B></FONT></TD>";
	vCode = vCode + "</TR>";
	
	return vCode;
}

Calendar.prototype.cal_data = function() {
	var vDate = new Date();
	vDate.setDate(1);
	vDate.setMonth(this.gMonth);
	vDate.setFullYear(this.gYear);

	var vFirstDay=vDate.getDay();
	var vDay=1;
	var vLastDay=Calendar.get_daysofmonth(this.gMonth, this.gYear);
	var vOnLastDay=0;
	var vCode = "";

	/*
	Get day for the 1st of the requested month/year..
	Place as many blank cells before the 1st day of the month as necessary. 
	*/

	vCode = vCode + "<TR>";
	for (i=0; i<vFirstDay; i++) {
		vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(i) + "><FONT SIZE='2' FACE='" + fontface + "'> </FONT></TD>";
	}

	// Write rest of the 1st week
	for (j=vFirstDay; j<7; j++) {
		vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(j) + "><FONT SIZE='2' FACE='" + fontface + "'>" + 
			"<A HREF='#' " + 
				"onClick=\"self.opener.document." + this.gReturnItem + ".value='" + 
				this.format_data(vDay) + 
				"';window.close();\">" + 
				this.format_day(vDay) + 
			"</A>" + 
			"</FONT></TD>";
		vDay=vDay + 1;
	}
	vCode = vCode + "</TR>";

	// Write the rest of the weeks
	for (k=2; k<7; k++) {
		vCode = vCode + "<TR>";

		for (j=0; j<7; j++) {
			vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(j) + "><FONT SIZE='2' FACE='" + fontface + "'>" + 
				"<A HREF='#' " + 
					"onClick=\"self.opener.document." + this.gReturnItem + ".value='" + 
					this.format_data(vDay) + 
					"';window.close();\">" + 
				this.format_day(vDay) + 
				"</A>" + 
				"</FONT></TD>";
			vDay=vDay + 1;

			if (vDay > vLastDay) {
				vOnLastDay = 1;
				break;
			}
		}

		if (j == 6)
			vCode = vCode + "</TR>";
		if (vOnLastDay == 1)
			break;
	}
	
	// Fill up the rest of last week with proper blanks, so that we get proper square blocks
	for (m=1; m<(7-j); m++) {
		if (this.gYearly)
			vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(j+m) + 
			"><FONT SIZE='2' FACE='" + fontface + "' COLOR='gray'> </FONT></TD>";
		else
			vCode = vCode + "<TD WIDTH='14%'" + this.write_weekend_string(j+m) + 
			"><FONT SIZE='2' FACE='" + fontface + "' COLOR='gray'>" + m + "</FONT></TD>";
	}
	
	return vCode;
}

Calendar.prototype.format_day = function(vday) {
	var vNowDay = gNow.getDate();
	var vNowMonth = gNow.getMonth();
	var vNowYear = gNow.getFullYear();

	if (vday == vNowDay && this.gMonth == vNowMonth && this.gYear == vNowYear)
		return ("<FONT COLOR=\"RED\"><B>" + vday + "</B></FONT>");
	else
		return (vday);
}

Calendar.prototype.write_weekend_string = function(vday) {
	var i;

	// Return special formatting for the weekend day.
	for (i=0; i<weekend.length; i++) {
		if (vday == weekend[i])
			return (" BGCOLOR=\"" + weekendColor + "\"");
	}
	
	return "";
}

Calendar.prototype.format_data = function(p_day) {
	var vData;
	var vMonth = 1 + this.gMonth;
	vMonth = (vMonth.toString().length < 2) ? "0" + vMonth : vMonth;
	var vMon = Calendar.get_month(this.gMonth).substr(0,3).toUpperCase();
	var vFMon = Calendar.get_month(this.gMonth).toUpperCase();
	var vY4 = new String(this.gYear);
	var vY2 = new String(this.gYear.substr(2,2));
	var vDD = (p_day.toString().length < 2) ? "0" + p_day : p_day;

	switch (this.gFormat) {
		case "MM\/DD\/YYYY" :
			vData = vMonth + "\/" + vDD + "\/" + vY4;
			break;
		case "MM\/DD\/YY" :
			vData = vMonth + "\/" + vDD + "\/" + vY2;
			break;
		case "MM-DD-YYYY" :
			vData = vMonth + "-" + vDD + "-" + vY4;
			break;
		case "MM-DD-YY" :
			vData = vMonth + "-" + vDD + "-" + vY2;
			break;

		case "DD\/MON\/YYYY" :
			vData = vDD + "\/" + vMon + "\/" + vY4;
			break;
		case "DD\/MON\/YY" :
			vData = vDD + "\/" + vMon + "\/" + vY2;
			break;
		case "DD-MON-YYYY" :
			vData = vDD + "-" + vMon + "-" + vY4;
			break;
		case "DD-MON-YY" :
			vData = vDD + "-" + vMon + "-" + vY2;
			break;

		case "DD\/MONTH\/YYYY" :
			vData = vDD + "\/" + vFMon + "\/" + vY4;
			break;
		case "DD\/MONTH\/YY" :
			vData = vDD + "\/" + vFMon + "\/" + vY2;
			break;
		case "DD-MONTH-YYYY" :
			vData = vDD + "-" + vFMon + "-" + vY4;
			break;
		case "DD-MONTH-YY" :
			vData = vDD + "-" + vFMon + "-" + vY2;
			break;

		case "DD\/MM\/YYYY" :
			vData = vDD + "\/" + vMonth + "\/" + vY4;
			break;
		case "DD\/MM\/YY" :
			vData = vDD + "\/" + vMonth + "\/" + vY2;
			break;
		case "DD-MM-YYYY" :
			vData = vDD + "-" + vMonth + "-" + vY4;
			break;
		case "DD-MM-YY" :
			vData = vDD + "-" + vMonth + "-" + vY2;
			break;

		case "YYYY-MM-DD" :
			vData = vY4+"-"+vMonth +"-"+ vDD;
			break;



		default :
			vData = vMonth + "\/" + vDD + "\/" + vY4;
	}

	return vData;
}

function Build(p_item, p_month, p_year, p_format) {
	var p_WinCal = ggWinCal;
	gCal = new Calendar(p_item, p_WinCal, p_month, p_year, p_format);

	// Customize your Calendar here..
	gCal.gBGColor="white";
	gCal.gLinkColor="black";
	gCal.gTextColor="black";
	gCal.gHeaderColor="darkgreen";

	// Choose appropriate show function
	if (gCal.gYearly)	gCal.showY();
	else	gCal.show();
}

function show_calendar() {
	/* 
		p_month : 0-11 for Jan-Dec; 12 for All Months.
		p_year	: 4-digit year
		p_format: Date format (mm/dd/yyyy, dd/mm/yy, ...)
		p_item	: Return Item.
	*/

	p_item = arguments[0];
	if (arguments[1] == null)
		p_month = new String(gNow.getMonth());
	else
		p_month = arguments[1];
	if (arguments[2] == "" || arguments[2] == null)
		p_year = new String(gNow.getFullYear().toString());
	else
		p_year = arguments[2];
	if (arguments[3] == null)
		p_format = "YYYY-MM-DD";
	else
		p_format = arguments[3];

	vWinCal = window.open("", "Calendar", 
		"width=250,height=250,status=no,resizable=no,top=200,left=200");
	vWinCal.opener = self;
	ggWinCal = vWinCal;

	Build(p_item, p_month, p_year, p_format);
}
/*
Yearly Calendar Code Starts here
*/
function show_yearly_calendar(p_item, p_year, p_format) {
	// Load the defaults..
	if (p_year == null || p_year == "")
		p_year = new String(gNow.getFullYear().toString());
	if (p_format == null || p_format == "")
		p_format = "YYYY-MM-DD";

	var vWinCal = window.open("", "Calendar", "scrollbars=yes");
	vWinCal.opener = self;
	ggWinCal = vWinCal;

	Build(p_item, null, p_year, p_format);
}

// ******************************************************************************************************END CALENDAR






// ******************************************************************************************************BEGIN DPE

function putvalue(id,v){
	
	refstr = "arrItems"+id+"["+preID[id]+"][1]"; 	// to get last item price to compare with the current price onchange
	refstrval = eval(refstr);			// evalulate strng

	str = "arrItems"+id+"["+v+"][1]";
	strval = eval(str);


	diff = strval-refstrval;
	newprice =  overallprice+diff;
	drawlist(id,v);				// redraw category dynamic relative prices
	// document.forms[0].cal.value = diff;		//debug   [ diff is the dynamics difference value between the last and current price ]
	document.all['price'].innerHTML = newprice;
	document.all['pricebottom'].innerHTML = newprice;
	preID[id] = v;
	overallprice = newprice
}

function drawlist(id,defitem){

//	cat = "document.forms[0].cat"+id;
	cat = "document.custom.cat"+id;
	cats = eval(cat);
	arrItem = "arrItems"+id;
	arrItems = eval(arrItem);

	for (i=0;i<arrItems.length;i++)
	{
		 var defaultprice = arrItems[defitem][1];
		 var desc = arrItems[i][0];
		 var prod_id = arrItems[i][2];
		 var pricediff = arrItems[i][1]-defaultprice;
		 
		if(pricediff != 0){
			sign = (pricediff < 0 ) ? "-" : "+" ;
			pricediff = Math.abs(pricediff);
			
			//desc += "[ "+arrItems[i][1]+" ] ";
			desc += " ["+sign+pricediff+ " บาท]";
		}
		cats.options[i] = new Option(desc,prod_id);
		cats.selectedIndex = defitem;
	}
}

// ******************************************************************************************************END DPE 


// BEGIN CREAT SUITE DESC.
	var cost = 0;
	var total = 0;
	var surplus = 0;

function sum(surplus,box,obj){

	doc = eval("document.frm");

	box.value=(surplus.value/100+1)*obj.value;
	

	cost = parseInt(doc.mainboard.value);
	cost += parseInt(doc.processor.value);
	cost += parseInt(doc.harddisk.value);
	cost += parseInt(doc.memory.value);
	cost += parseInt(doc.monitor.value);
	cost += parseInt(doc.modem.value);
	cost += parseInt(doc.speaker.value);

	
	total = parseInt(doc.price_mainboard.value);
	total += parseInt(doc.price_processor.value);
	total += parseInt(doc.price_harddisk.value);
	total += parseInt(doc.price_memory.value);
	total += parseInt(doc.price_monitor.value)
	total += parseInt(doc.price_modem.value);
	total += parseInt(doc.price_speaker.value);
	
	doc.total.value = Math.round(total*100/100);
	doc.vat.value = Math.round(7/100*total);
	doc.gtotal.value = Math.round((total*100+doc.vat.value*100)/100);
	doc.cost.value = cost;
}

function gain(sell){
	
	doc = eval("document.frm");
	cost = parseInt(doc.mainboard.options.value);
	cost += parseInt(doc.processor.options.value);
	cost += parseInt(doc.harddisk.options.value);
	cost += parseInt(doc.memory.options.value);
	cost += parseInt(doc.monitor.options.value);
	cost += parseInt(doc.modem.options.value);
	cost += parseInt(doc.speaker.options.value);
	sell = parseInt(sell);
	doc.margin.value = sell-cost;
	doc.percentage.value = Math.round(((sell-cost)/cost)*100);
}
// END CREAT SUITE DESC.

function winpop_addnewtemplate(){
	newwin = window.open("/acl/addtemplate.html","test","width=600,height=150,status=no,toolbar=no,resize=no,border=0,menubar=no,outerWidth=0,title=0");
}

function submitform(){
	//window.opener.location.href = document.addtemplate.url.value;
	window.opener.location.reload(false);
}

function isCheck(x){
	if(x.checked){
		document.frm.pick.value += x.name+"::";
	}else{
		strg = document.frm.pick.value;
		pre = x.name+"::";
		eval("re = /"+pre+"/");
		document.frm.pick.value = strg.replace(re,"");
	}
}


function isCheck_Multi_Items(x,y){
	
	
	doc = eval("self.opener.document.frm."+y);
	
	if(x.checked){
		doc.value += x.name+"::";
	}else{
		strg = doc.value;
		pre = x.name+"::";
		eval("re = /"+pre+"/");
		doc.value = strg.replace(re,"");
	}
}

function winpop(x){
	win = window.open(x,"yahoo","width=400,height=600,status=no,toolbar=no,resize=no,scrollbars=1");
}

function pickthis(a,b){
	self.opener.document.frm.assetid.value=a;
	self.opener.document.frm.product_id.value=b;
}



function validateeven(){
	evennumber = document.frm.cadult.value;
		if (evennumber%2){
			alert("กรุณาระบุจำนวน ให้ถูกต้อง เนื่องจากท่านกำลังที่จะเลือกห้องพัก\n ซึ่งสามารถพักได้ห้องละสองท่าน ฉะนั้นท่านควรระบุเป็นเลขคู่\n ดังเช่น 2,4,6 หรือ 8 ท่าน เป้นต้น");
			return false;
		}
	return true;
}


function winpop_x(w,h,x){
	var windowprops = "status=yes,location=no,scrollbars=yes,menubars=no,toolbars=no,resizable=n,width=" + w + ",height=" + h;
	win = window.open(x,"yahoo",windowprops);
}



function winpop_noscroll(w,h,x){
	var windowprops = "status=no,location=no,scrollbars=no,menubars=no,toolbars=no,resizable=n,width=" + w + ",height=" + h;
	win = window.open(x,"yahoo",windowprops);
}


