var tindex=0;
var final_sum=0,sum=0,shipmentprice=0;
var fields=27;
var price = new Array();
var product = new Array();
var pid = new Array();
var recid = new Array();
var ammount = new Array();
var categ = new Array();
var prods_counter=0;
var default_line="";//"<img src='/build/arrow.gif' align='absmiddle' width='17' height='17'>";
var fmTimer;
var faded=true;
var fadeObj;

for (i=0;i<=fields;i++){
        price[i] = 0;
        product[i] = "0";
        pid[i] = "";
        recid[i] = "";
        ammount[i] = 0;
        categ[i]="";

}

//--------------------- Print Field ----------------------------
function print_field(category,indx,row){
        categ[indx]=category;
        document.write
("<tr onmouseover=\"this.style.backgroundColor='#DEDEDE';\" onmouseout=\"this.style.backgroundColor='';\"  height=20>"
  +"<th onClick=\"oFrame.style.display='none'\" width=120 align=left><img src='./build/img/"+indx+".gif'> <b>"+category+"</b></th><th>"
        +"<table style='border-collapse: collapse' bordercolor='#628AC5' border=1>"
          +"<tr>"
                +"<th onclick='show_products(event,this,"+indx+")' style='cursor: hand;' width=100%>"
                +default_line+"</th>"
                +"<th onclick=\"show_products(event,this,"+indx+")\" style='cursor: hand;' >"
                +"<img src='./build/img/scroll.gif' width='20' height='18'></th>"
                +"<th onClick=\"oFrame.style.display='none'\" valign=top><input type=\"button\" value=\"info\" style=\"border: #C4B0AB 1px solid; background-color: #F1F1F1; color: #5C5C5C; font-weight: bold\" onclick='show_desc("+indx+")'></th>"
          +"</tr></table>"
  +"</th>"
  +"<th align='right' onClick=\"oFrame.style.display='none'\" ></th>"
  +"<th align='center' onClick=\"oFrame.style.display='none'\" width=35>"
    +"<input type=hidden name=products_id"+indx+" value='-1'><select name='qty"+indx+"'  onchange='calc_subtotal(mainform);calc_total(mainform);'>");
        document.write ("<option value=1 selected>1</option>");
        for (i=2;i<=10;i++)        document.write ("<option value="+i+">"+i+"</option>");
        document.write ("</select></th></tr>");
}
//--------------------- Fader ----------------------------
function Fade(){
  if (!faded) {
        faded=true;
        faderObj.innerHTML=default_line;
        window.clearTimeout(fmTimer);
  }else{
          faded=false;
        fmTimer=window.setTimeout("Fade()",2000);
  }
}
//--------------------- Fade Row ----------------------------
function fade_row(row){
        if (!faded){
                faded=true;
                faderObj.innerHTML=default_line;
                window.clearTimeout(fmTimer);
        }
        var note="";
//        switch (row){
//                case 2:
//                        if (!recid[1]) note=note1;
//                        break;
//                case 3:
//                        if (!recid[2]) note=note2;
//                        break;
//        }
        if (note!="") {
                faderObj = document.getElementById("prod_table").rows[row].cells[1].childNodes[0].rows[0].cells[0];
                faderObj.innerHTML=default_line+note;
                Fade();
                return false;
        }else
                return true;
}
//--------------------- Show Products ----------------------------
function show_products(evt,e,pindex,row){
  if (pindex!=tindex){
        document.getElementById("oFrame").style.display="none";
        tindex=pindex;
  }
  if (!fade_row(pindex+1)) return;
  var sURL="prduct_list.php?row="+pindex+"&currency="+currency+"&dcpu="+recid[row]+"&dmem="+product[pindex];
  if (document.getElementById("oFrame").innerHTML==""){
	  document.getElementById("oFrame").innerHTML="<iframe name='oiFrame' id='oiFrame' height='100%' width=100% border='0' frameborder='0'></iframe>";
  }
  var buffer="<html><head><style>TD,TH,BODY{font-family:Arial,Tahoma,Helvetica,sans-serif;font-size:9pt;}TH{background-color:#86A5D2;filter:progid:DXImageTransform.Microsoft.Gradient(GradientType=0,StartColorStr='#0086A5D2',EndColorStr='#C0FFFFFF');font-style:italic;border:1px solid Black;cursor:default;}.select_table{BORDER-COLLAPSE:collapse;border:1px ridge;background-color:#F5F5F5;}tr{cursor:hand;}BODY{overflow: auto;margin: 0 0 0 0;background-color: #F5F5F5;}</style>";
  buffer+="<table style='BORDER-COLLAPSE: collapse' borderColor='#86A5D2' border='1' width='100%'>";
switch (pindex){
 case 1:
        add_product('-1','','','','2');
        sURL+="&select="+product[pindex]+"&currency="+currency;
        oiFrame.document.write(buffer+text_please_wait);
        window.open(sURL,"oiFrame");
        break;
  case 2:
        oiFrame.document.write(buffer+text_please_wait);
        window.open(sURL,"oiFrame");
        break;
  case 0:
        add_product('-1','','','','1');
        add_product('-1','','','','2');
  default :
        sURL+="&select="+product[pindex]+"&currency="+currency;
        oiFrame.document.write(buffer+text_please_wait);
        window.open(sURL,"oiFrame");
        if (pindex){
        buffer+="<tr onmouseover=\"this.style.backgroundColor='#86A5D2';\" onmouseout=\"this.style.backgroundColor='';\" onclick=\"parent.add_product('','','','','"+pindex+"');\"><td align='center' colspan=2><b>"+text_deselect_items+"</b></td></tr>";
        oiFrame.document.write(buffer+loadRow(pindex)+"</table>");
        window.open(sURL,"oiFrame");
        }
        break;
    }
    if (document.getElementById("oFrame").style.display=="none") {
        var categoryid=-1;
        var aTag;
        tab=e.parentNode; //TR
        aTag=tab;
        var leftpos=0;
        var toppos=0;
        do {
                aTag = aTag.offsetParent;
                leftpos += aTag.offsetLeft;
                toppos += aTag.offsetTop;
        } while(aTag.tagName!="BODY");

        var PopupHeight=200;
        var TotTop=tab.offsetTop+tab.offsetHeight +toppos;

        document.getElementById("oFrame").style.left =tab.offsetLeft+leftpos+1;
        if (evt.clientY+PopupHeight+10>document.body.clientHeight){
                TotTop-=PopupHeight+tab.offsetHeight;
        }  
        document.getElementById("oFrame").style.height=PopupHeight;
        document.getElementById("oFrame").style.top = TotTop;
        document.getElementById("oFrame").style.width = tab.cells[0].offsetWidth+tab.cells[1].offsetWidth+1;
        document.getElementById("oFrame").style.display="inline";
    }else{
      document.getElementById("oFrame").style.display="none";
    }
}
//--------------------- Load Row ----------------------------
function loadRow(indx){
        var j;
        var buffer="";
        for (j=0;(l[indx][j]);j++) 
		  buffer+=print_line(indx,j);
        if (!buffer) 
          buffer = "";
        return buffer;
}
//--------------------- Print Line ----------------------------
function print_line(row,line){
  var buffer="";
  if (l[row][line][1]){
        var pdesc2 = l[row][line][1].replace(/:inc:/gi, '"')
        re2 = new RegExp ('\'', 'gi') ;
        l[row][line][1] = l[row][line][1].replace(re2, ":tag:")
        buffer+= "<tr onclick=\"parent.add_product('"+l[row][line][0]+"','"+l[row][line][1]+"','"+l[row][line][2]+"','"+l[row][line][3]+"',"+l[row][line][4]+");\" onmouseover=\"this.style.backgroundColor='#86A5D2';\" onmouseout=\"this.style.backgroundColor='';\">"
+"<td>"+pdesc2+"</td><td align='right' width=70>&nbsp;"+l[row][line][2]+""+currency+"</td></tr>";
  }else{
        buffer+=print_title(l[row][line][0]);
  }
  return buffer;
}
//--------------------- Print Title ----------------------------
function print_title(title){
        return "<tr><th align='center' colspan='2'>"+title+"</th></tr>";
}

//--------------------- Calculate Subtotal ----------------------------
function calc_subtotal(form){
        var sum=0

        for (i=0;i<=fields;i++){
                if (price[i]>0){
                        sum=sum+parseFloat(price[i]*(form.elements["qty"+(i-1)].selectedIndex+1));
                }
        }
        var lines=form.select1.length
        var softprice=0;
        for (i=1;i<lines;i++){
                if (form.select1.options(i).selected){
                        softprice+=parseFloat(form.select1.options(i).price)*parseFloat(form.qty100.selectedIndex+1);
                }
        }
        form.sum.value=formatnumber(sum+softprice);
}

//--------------------- Calculate Sum ----------------------------
function calc_total(form){
    	form.totsum.value=currency_left+" "+formatnumber(parseFloat(form.sum.value))+" "+currency_right;
}

function calc_total_tmp(form){
        var sum=0;
        var final_sum;
        for (i=0;i<=fields;i++){
                if (price[i]>0){
                        sum=sum+parseFloat(price[i]*(form.elements["qty"+(i-1)].selectedIndex+1));
                }
        }
        var lines=form.select1.length
        var softprice=0;
        for (i=1;i<lines;i++){
                if (form.select1.options(i).selected){
                        softprice+=parseFloat(form.select1.options(i).price)*parseFloat(form.qty100.selectedIndex+1);
                }
        }
        sum=formatnumber(sum+softprice);
        final_sum=sum;
        form.sum.value=final_sum;
        form.totsum.value=currency_left+" "+final_sum+" "+currency_right;


}
//--------------------- Enabel/Disable Payments ----------------------------'
function show_payments(form){
  if (form.payment_mode.options(form.payment_mode.selectedIndex).value!="CASH"){
        form.payments.disabled =false;
        form.each.disabled =false;
  }else{
          form.payments.options(0).selected = true;
        form.payments.disabled =true;
        form.each.disabled = true;
  }
}

//--------------------- ValidateForm ----------------------------
function ValidateForm(form){
        var err="";
        if (!pid[1]) err+="Please select CPU\n";
        if (!pid[2]) err+="Please select Mother Board\n";
        if (!pid[3]) err+="Please select Memory\n";
        if (form.firstname.value=="") err+="No first name was entered\n";
        if (form.lastname.value=="") err+="No last name was entered\n";
        if (form.city.value=="") err+="No city was entered\n";
        if (form.address.value=="") err+="No address was entered\n";
        if (form.tel.value=="") err+="No telephone was entered\n";
        if (err!=""){
                alert(err);
                return false;
        }
        return true;
}

//--------------------- Form check before submission ----------------------------
function mainform_onsubmit(form,sact,fields)
{
        if (form.sum.value=="0"){
                alert ("You must have products in order");
                return false;
        }
        for (i=0;i<fields;i++){
                ammount[i+1]=form.elements["qty"+i].selectedIndex+1;
        }
        var urltemp="compbuild.php?action=add_products&products_id=";
        var urltempammount="&product_ammount="

        form.product.value="";
        form.pid.value="";
        form.price.value="";
        form.ammount.value="";
        form.recid.value="";
        for (i=0;i<=fields;i++){
                form.product.value+=product[i]+"::";
                form.pid.value+=pid[i]+"::";
                form.price.value+=price[i]+"::";
                form.ammount.value+=ammount[i]+"::";
                form.recid.value+=recid[i]+"::";
                if (recid[i]){
                    urltemp+=recid[i]+",";
                    urltempammount+=ammount[i]+",";
                }
        }
        var lines=form.select1.length
        for (i=1;i<lines;i++){
                if (form.select1.options(i).selected){
                        form.product.value+=form.select1.options(i).value+";;";
                        form.price.value+=form.select1.options(i).price;
                        form.pid.value+=form.select1.options(i).pid;
                        form.recid.value+=form.select1.options(i).recid;
                        form.ammount.value+=(form.qty100.selectedIndex+1)+";;";

                }
        }
 if (sact==2){
        urltemp+=urltempammount;
        form.action=urltemp;
        form.target="_self";
        form.submit();
}else if (sact==1){
        form.action="print.php";
        form.target="_blank";
        form.submit();
}
}
//----------------- Format float number (2 digits after dot) ---------------
function formatnumber(num,num_after_dot){
        if (!num_after_dot) num_after_dot=2;
        if (num<0.05) num=0;
        var snum = (String) (num);
        var is_dot_ok=snum.indexOf('.')
        if (!(is_dot_ok==-1)){
                snum = snum.substr(0,is_dot_ok+num_after_dot+1);
                if ((snum.length-is_dot_ok)==2){
                        snum=snum+"0"
                }else{ 
                    if ((snum.length-is_dot_ok)==1){
                        snum=snum+"00"
                    }
                }
        }
        return snum;
}
//--------------------- Adding Product To The List -------------------------
function add_product(ipid,ipname,iprice,irecid,row){
        row++;
        var enable=false;
        if (ipid=='-1'){
                enable=true;
                ipid="";
        }
        ipname = ipname.replace(/:inc:/gi, '"')
        ipname = ipname.replace(/:tag:/gi, '\'')
        var prods_row = document.getElementById("prod_table").rows[row];
        var title_cell=prods_row.cells[1].childNodes[0].childNodes[0].childNodes[0].cells[0];
        var price_cell=prods_row.cells[2];
        if (!ipname){
                title_cell.innerHTML=default_line;
                price_cell.innerHTML="";
        }else{
                title_cell.innerHTML="&nbsp;"+ipname;
                price_cell.innerHTML=currency_left+" "+iprice+" "+currency_right;
        }
        price[row]=iprice;
        product[row]=ipname;
        pid[row]=ipid;
        recid[row]=irecid;
        if (!enable) document.getElementById("oFrame").style.display="none";
        calc_total_tmp(document.mainform);
}
//----------------- Show Description ---------------
function show_desc(row){
        row++;
        if (recid[row])
                window.open ("product_info.php?products_id="+recid[row],'new', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=Yes,resizable=yes,copyhistory=yes');
}