﻿
// Result.js

catalogRow=0;  
resultcount=200;
catcount=0;
cartRow=0;
itemCount=0;
yearcount=70;
make="";
model="";
category="";
subcategory="";
year="";
brand="";
catalog="";
yearChanged=false;
var img = new Image;

document.onload=fnStart();


function fnStart() {
    //add row references 
    //grows=igtbl_getGridById('MakeGrid').Rows;
    ourInterval = setInterval('fnReady()', 500);
}

function fnReady() {
    if (typeof ResultsGrid == 'undefined') {
        return;  
     }
    else {
        clearInterval(ourInterval);
        fnLoad();
     }
}


function fnLoad() {
   
   document.getElementById('divSearch').onclick=function(){fnSearch();};
   document.getElementById('imgSearch').onclick=function(){fnSearch();};
   document.getElementById('divCart').onclick=function(){fnShowCart();};
   document.getElementById('imgCart').onclick=function(){fnShowCart();};
   document.getElementById('btnAddToCart').onclick=function(){fnAddToCart();};
   document.getElementById('selYear').onchange=function(){fnDisplayResults();};
   document.getElementById('selBrand').onchange=function(){fnDisplayCatalogs();};
   document.getElementById('selPartType').onchange=function(){fnDisplayItems();};
   img.onload=function(){fnDisplayImage();};
   fnDisplayYears();

}

function fnDisplayYears(){
    document.getElementById('selYear').options[0] = new Option("(ALL)");
    for (rr=1; rr<yearcount; rr++){
          rw=rr;
	      document.getElementById('selYear').options[rr] = new Option(2009-rw+1);
    	 
     } 
    //Clear Selections
    document.getElementById('selYear').selectedIndex=0;
}

function fnDisplayResults() {
    fnDisplayBrands();
    if (yearChanged==true) {
        yearChanged=false;
        fnDisplayBrands();
        
   } 
}
function fnDisplayCatalogs() {
    document.getElementById('selPartType').selectedIndex=0;
    fnDisplayBrands();
}
function fnDisplayItems() {
    //document.getElementById('selYear').selectedIndex=0;
    fnDisplayBrands();
}

function fnShowCart() {
    if (itemCount==0) {
        alert("No items have been added to the Parts List. First select a line and then click Add To Parts List ...")
        return; 
   }
   document.getElementById('divPic').style.visibility='hidden';
   parent.document.getElementById('fraMMCS').style.visibility='hidden';
   parent.document.getElementById('fraResults').style.visibility='hidden';
   parent.document.getElementById('fraCart').style.visibility='visible';
 }

function fnSearch() {
   document.getElementById('divPic').style.visibility='hidden';
   frameMMCS=parent.frames[0]; 
   frameResults=parent.frames[1];  
   parent.document.getElementById('fraResults').style.visibility='hidden';
   parent.document.getElementById('fraCart').style.visibility='hidden';
   parent.document.getElementById('fraMMCS').style.visibility='visible';
 
}

function fnAddToCart() {
   
   if (ResultsGrid.getSelectedItem() == null) {
        alert('Please select a row before adding to cart ...');
        return;
   } 
   cartRow=0;
   row=ResultsGrid.getSelectedItem().getIndex();
   
   //Mod:040210
   if (parent.frames[1].ResultsGrid.getItem(row).getCell(9).getValue()=="StoreOnly") {
      alert( "Unfortunately this item cannot be shipped by courier or Australia Post and is therefore not available from our online store. This item can be purchased from your local store - please see our store locator for your nearest store.")
      return;       
   }
   
   
   //check for existing
   for (grdRow=0; grdRow<10; grdRow++){
        if (parent.frames[2].CartGrid.getItem(grdRow).getCell(7).getValue() >'$' ){
            cartRow=cartRow+1; 
            if (parent.frames[2].CartGrid.getItem(grdRow).getCell(6).getValue() == parent.frames[1].ResultsGrid.getItem(row).getCell(6).getValue() ) {
                alert("This part is already added to cart ...");
                return;
            }
        } else {
             break;
        } 
    }
   if (cartRow>9) {
        alert("You have reached the maximum number of items per online order...");
        return;
     } 
   // add to cart 
    parent.frames[2].CartGrid.getItem(cartRow).getCell(0).setValue(parent.frames[0].make + ' ' + parent.frames[1].ResultsGrid.getItem(row).getCell(0).getValue());
    for (grdCol=1; grdCol<8; grdCol++){
       parent.frames[2].CartGrid.getItem(cartRow).getCell(grdCol).setValue(parent.frames[1].ResultsGrid.getItem(row).getCell(grdCol).getValue());
    }
   parent.frames[2].CartGrid.getItem(cartRow).getCell(8).setValue(1); 
   parent.frames[2].CartGrid.getItem(cartRow).getCell(9).setValue("x");
   parent.frames[2].CartGrid.getItem(cartRow).getCell(10).setValue(parent.frames[1].ResultsGrid.getItem(row).getCell(8).getValue());
   parent.frames[2].CartGrid.getItem(cartRow).getCell(11).setValue(parent.frames[1].ResultsGrid.getItem(row).getCell(9).getValue());
   fnTotalCart(); 
}

function fnTotalCart() {
    itemCount=0;
    cartTotal=0;
     for (grdRow=0; grdRow<10; grdRow++){
            if (parent.frames[2].CartGrid.getItem(grdRow).getCell(7).getValue() >'$' ){
                itemCount=itemCount +1;
                cartTotal=cartTotal + fnVal( parent.frames[2].CartGrid.getItem(grdRow).getCell(7).getValue() )* fnVal( parent.frames[2].CartGrid.getItem(grdRow).getCell(8).getValue() );
                parent.frames[2].document.getElementById('CartGrid_i' + grdRow +'_c8').style.background='#FFFF80'; 
            } else {
                if ((grdRow/2) ==parseInt(grdRow/2)) {
                    parent.frames[2].document.getElementById('CartGrid_i' + grdRow +'_c8').style.background='whitesmoke'; 
                } else {
                    parent.frames[2].document.getElementById('CartGrid_i' + grdRow +'_c8').style.background='white'; 
                }
            } 
        }
        parent.frames[2].document.getElementById('divSubTotal').innerHTML = '$' + cartTotal.toFixed(2);
        if (itemCount==1) {
            parent.frames[1].document.getElementById('divItemCount').innerHTML= "(" + itemCount + " item selected)" 
        } else {
            parent.frames[1].document.getElementById('divItemCount').innerHTML= "(" + itemCount + " items selected)" 
        } 
}


//Brands
function fnDisplayBrands(){
   fnClearRows();
   parent.frames[1].document.getElementById('divCount').innerHTML= "";
   catalog="";
   exitSearch=false;
   maxResults=false; 
  
    strsubcategory = strReplaceAll(subcategory,"&","^");
    var SrchSQL = "Select distinct Status,[Catalog] from VCat where [Catalog]>'0'  and Category='" + category + "' and SubCategory='" + strsubcategory + "' and Make = '" + make + "' and Model = '" + model +"'";
    
    ii=document.getElementById('selYear').selectedIndex;
	year=document.getElementById('selYear').options[ii].innerHTML; 
	
	ii=document.getElementById('selBrand').selectedIndex;
	brand=document.getElementById('selBrand').options[ii].innerHTML; 
	
	ii=document.getElementById('selPartType').selectedIndex;
	parttype=document.getElementById('selPartType').options[ii].innerHTML; 
    
    if (fnVal(year)>0) {
         var SrchSQL = SrchSQL + " and " + year + " >= FromYear" ;
         var SrchSQL = SrchSQL + " and " + year + " <= ToYear" ;
    } 
    if (brand>"(ALL)") {
         strcatalog = strReplaceAll(brand,"amp;",""); 
         strcatalog = strReplaceAll(strcatalog,"&","^"); 
         var SrchSQL = SrchSQL + " and  [Catalog] = '" + strcatalog +"'" ;
    } 
    
    var SrchSQL = SrchSQL + " order by Status,[Catalog]";
    var SrchSQL = strReplaceAll(SrchSQL,"&","^");
	var SrchSQL = strReplaceAll(SrchSQL,"<","`");
    var db = "v";
    var dblcn= "";
    var CountSQL="";
    DBLocation="c";
    if (window.XMLHttpRequest){
        var oXMLHTTP = new XMLHttpRequest();
    } else {
         var oXMLHTTP = new ActiveXObject( "Microsoft.XMLHTTP" );
    } 
    var varServer =window.location.hostname;
    var sURL = "./iCatServer.aspx?sql=" + SrchSQL + "&lcn=" + DBLocation + "&db=" + db;

    // Execute the request
    try {
        oXMLHTTP.open( "GET", sURL, false );
        oXMLHTTP.send(null);
    }
    catch (e) {
        alert("Web Service Unavailable..."+e.message);
        return;
    }

    dxResult=oXMLHTTP.responseText;


    catalogO=fnCreateDXObject(dxResult);

    oldcatalogRow=catalogRow;
    catalogRow=0;  
    if (catalogO.rowcount>0) {
        for (catrow=0; catrow<catalogO.rowcount; catrow++){
               catalog= catalogO.row[catrow].Catalog; 
               newbrand=true ;
              if (maxResults==false) {
                    fnDisplayCatDescription();
                    
                    if (exitSearch==true) {
                        return;
                    }
                    
              }   
             
		 } 
		     
     }
      
    document.body.style.cursor='default' ;
      
    if (catalogRow>0) {
           
        
          if (document.getElementById('selPartType').selectedIndex==0) {
              fnDisplayPartType();
         }  
          
    } else { 
         if (fnVal(year)==0) {
           alert('No Matching results...');
         } else {
            alert('No Matching results for the year ' + year + '. Now displaying ALL years to expand the results ... ');
            parent.frames[0]. YearGrid.selectCell(0,0);
            parent.frames[0]. YearGrid.getItem(0).ensureVisible();
            parent.frames[1].document.getElementById('selYear').selectedIndex=0;
            yearChanged=true; 
            year="(ALL)"
        }    
    }
   
   
} 




function fnDisplayCatDescription(){
	    SrchSQL = "Select top " + resultcount + " * from BrandPart where (Make = '" + make + "' and Model='" + model + "'";
	    SrchSQL=SrchSQL + " and CatalogName='" + catalog + "'"
	    SrchSQL=SrchSQL + " and Display=true"
         if (fnVal(year)>0) {
             var SrchSQL = SrchSQL + " and " + year + " >= FromYear" ;
             var SrchSQL = SrchSQL + " and " + year + " <= ToYear" ;
        } 
       if (document.getElementById('selPartType').selectedIndex>0) {
             parttype = strReplaceAll(parttype,"amp;",""); 
             parttype = strReplaceAll(parttype,"&","^"); 
             var SrchSQL = SrchSQL + " and  [Item] = '" + parttype +"'" ;
        } 
        var SrchSQL=SrchSQL + " and Price>0 ) order by UID";
        
        //var db =  strReplaceAll(catalog,"&","^") ;
        var db = "v";
        var dblcn= "c";
        DBLocation="c";
	    var CountSQL="";
	   
	    var SrchSQL = strReplaceAll(SrchSQL,"&","^");
		var SrchSQL = strReplaceAll(SrchSQL,"<","`");
		
        if (window.XMLHttpRequest){
            var oXMLHTTP = new XMLHttpRequest();
        } else {
             var oXMLHTTP = new ActiveXObject( "Microsoft.XMLHTTP" );
        } 
        var varServer =window.location.hostname;
       
         var sURL = "./iCatServer.aspx?sql=" + SrchSQL + "&lcn=" + DBLocation + "&db=" + db;
        
       // Execute the request
        try {
            oXMLHTTP.open( "GET", sURL, false );
	        oXMLHTTP.send(null);
        }
        catch (e) {
	        alert("Web Service Unavailable..."+e.message);
	        return;
	    }
        
        dxResult=oXMLHTTP.responseText;
        catO=fnCreateDXObject(dxResult);
        oldcatcount=catcount;
        rw=0;
       
        if (catO.rowcount>0) {
            // scan columns
	        rw=0;    
            for (rr=0; rr<catO.rowcount; rr++){
                
				  if (catalogRow>resultcount) {
				       alert("Displaying first " + resultcount + " items. You may select a specific Year Catalogue or Item Type to refine results...)");
				       maxResults=true;
				       return;    
				 }
				 brand=catalog.split("_")[0] ;
				
				// Display

                parent.frames[1].ResultsGrid.getItem(catalogRow).getCell(0).setValue(catO.row[rr].Series);
                parent.frames[1].ResultsGrid.getItem(catalogRow).getCell(1).setValue(catO.row[rr].Years);
                parent.frames[1].ResultsGrid.getItem(catalogRow).getCell(2).setValue(catO.row[rr].Engine);
                parent.frames[1].ResultsGrid.getItem(catalogRow).getCell(3).setValue(brand);  
                parent.frames[1].ResultsGrid.getItem(catalogRow).getCell(4).setValue(fnTrim(catO.row[rr].Item) );  
                if (catO.row[rr].Description.length<50) {   
                    parent.frames[1].ResultsGrid.getItem(catalogRow).getCell(5).setValue(catO.row[rr].Description + ' ' + catO.row[rr].PartDesc);  
                } else {
                    parent.frames[1].ResultsGrid.getItem(catalogRow).getCell(5).setValue(catO.row[rr].PartDesc);  
                }  
                
                parent.frames[1].ResultsGrid.getItem(catalogRow).getCell(6).setValue(catO.row[rr].Part);
                parent.frames[1].ResultsGrid.getItem(catalogRow).getCell(7).setValue('$' + fnVal(catO.row[rr].Price).toFixed(2)); 
                
                //Mod:040210
                if ( catO.row[rr].XRefDisplayPart >'0' ) {
                   parent.frames[1].ResultsGrid.getItem(catalogRow).getCell(6).setValue(catO.row[rr].XRefDisplayPart); 
                }
                if ( fnVal(catO.row[rr].XRefPrice) >0  ) {
                   parent.frames[1].ResultsGrid.getItem(catalogRow).getCell(7).setValue('$' + fnVal(catO.row[rr].XRefPrice).toFixed(2));
                }
                
                if (catO.row[rr].Description.length<50) { 
                     parent.frames[1].ResultsGrid.getItem(catalogRow).getCell(8).setValue(catO.row[rr].Notes); 
                } else {
                     parent.frames[1].ResultsGrid.getItem(catalogRow).getCell(8).setValue(catO.row[rr].Description + catO.row[rr].Notes); 
                } 
                
                //Mod:040210
                parent.frames[1].ResultsGrid.getItem(catalogRow).getCell(9).setValue(catO.row[rr].SupplierCode); 
               
                if (catO.row[rr].StoreOnly=="True") {
                    parent.frames[1].ResultsGrid.getItem(catalogRow).getCell(9).setValue("StoreOnly");
                }  
                
                catalogRow=catalogRow+1;  
    		                 
	         } 
    		 document.getElementById('divCount').innerHTML= "Displaying " +  catalogRow + " items.";
    		 	 
	    } 
}  

function fnDisplayPartType(){
       
	    SrchSQL = "Select distinct Item from BrandPart where (Make = '" + make + "' and Model='" + model + "'";
	    ii=document.getElementById('selYear').selectedIndex;
	    year=document.getElementById('selYear').options[ii].innerHTML; 
	    ii=document.getElementById('selBrand').selectedIndex;
	    catalog=document.getElementById('selBrand').options[ii].innerHTML; 
	    if (document.getElementById('selBrand').selectedIndex>0) {
	        SrchSQL=SrchSQL + " and CatalogName='" + catalog + "'"
	    } else {
	       SrchSQL=SrchSQL +" and (";
	        for (rr=1; rr<document.getElementById('selBrand').length; rr++){
	            catalog=document.getElementById('selBrand').options[rr].innerHTML; 
	           if (rr>1) {
	                SrchSQL=SrchSQL + " or ";
	           } 
	            SrchSQL=SrchSQL + "CatalogName='" + catalog + "'";
	        } 
	        SrchSQL=SrchSQL +")";
	        
	    }
	   
	    SrchSQL=SrchSQL + " and Item>' .' and Price>0 and Display=true"
         if (fnVal(year)>0) {
             var SrchSQL = SrchSQL + " and " + year + " >= FromYear" ;
             var SrchSQL = SrchSQL + " and " + year + " <= ToYear" ;
        } 
       
        var SrchSQL=SrchSQL + ") order by Item";
        
        //var db =  strReplaceAll(catalog,"&","^") ;
        var db = "v";
        var dblcn= "c";
        DBLocation="c";
	    var CountSQL="";
	   
	    var SrchSQL = strReplaceAll(SrchSQL,"&","^");
		var SrchSQL = strReplaceAll(SrchSQL,"<","`");
		
        if (window.XMLHttpRequest){
            var oXMLHTTP = new XMLHttpRequest();
        } else {
             var oXMLHTTP = new ActiveXObject( "Microsoft.XMLHTTP" );
        } 
        var varServer =window.location.hostname;
       
         var sURL = "./iCatServer.aspx?sql=" + SrchSQL + "&lcn=" + DBLocation + "&db=" + db;
        
       // Execute the request
        try {
            oXMLHTTP.open( "GET", sURL, false );
	        oXMLHTTP.send(null);
        }
        catch (e) {
	        alert("Web Service Unavailable..."+e.message);
	        return;
	    }
        
        dxResult=oXMLHTTP.responseText;
        parttypeO=fnCreateDXObject(dxResult);
       
        rw=0;
        parent.frames[1].document.getElementById('selPartType').options.length=0;
        parent.frames[1].document.getElementById('selPartType').options[0] = new Option("(ALL)");
        if (parttypeO.rowcount>0) {
            // scan columns
	        rw=0;    
            for (rr=0; rr<parttypeO.rowcount; rr++){
                rw=rw+1;
				parent.frames[1].document.getElementById('selPartType').options[rw] = new Option(parttypeO.row[rr].Item);  
                                 
	         } 
    			 
	    }
	    parent.frames[1].document.getElementById('selPartType').selectedIndex=0; 
}  

function fnClearRows() {
 
            for (grdRow=0; grdRow<resultcount; grdRow++){
                for (grdCol=0; grdCol<10; grdCol++){
                   ResultsGrid.getItem(grdRow).getCell(grdCol).setValue(' ');
               }
           }
            //Clear Selections
            ResultsGrid.getItem(0).ensureVisible();
            ResultsGrid.selectItem(-1); 
}  

function fnShowPic() {
   document.getElementById('divPic').style.visibility='hidden';
   row=ResultsGrid.getSelectedItem().getIndex();
   //check for existing
   currPart= parent.frames[1].ResultsGrid.getItem(row).getCell(6).getValue();
   document.getElementById('imgProduct').src="./pics/blank.jpg";
   document.getElementById('lblPart').innerHTML="";
   
   img.src = "./pics/" + currPart + ".jpg" ; 
   
}
function fnDisplayImage() {
	document.getElementById('divPic').style.visibility='visible';
	img_width=120;
	img_height=80;
	
	if (img.height>0){
		ratio=img.width/img.height;
		img_width=80*ratio;
		
	}
	if (img_width>120) {
	    img_width=120;
	    img_height=120/ratio;
	    
	}
	
	document.getElementById('imgProduct').src=img.src;
	growImg = document.getElementById('imgProduct').style
	document.getElementById('imgProduct').src=img.src;
	
	growImg.width= img_width + "px";
	growImg.height= img_height + "px";	
	document.getElementById('lblPart').innerHTML= currPart;
}

function fnGrowPic() {
    
   // if  (growImg.width == img_width) {
        
        growImg.width= img_width*3 +"px";
	    growImg.height= img_height*3 +"px";
	   
	    document.getElementById('divPic').style.width= 268 +"px";
	    document.getElementById('divPic').style.height= 260 +"px";	
	    document.getElementById('divPic').style.top=150 +"px";
	    document.getElementById('divPic').style.left=340 +"px";
	    document.getElementById('lblPart').style.top=3 +"px";
	    document.getElementById('lblPart').style.left=7 +"px";
	    document.getElementById('lblPart').style.height=23 +"px";
	    document.getElementById('lblPart').style.width=247 +"px";
	 
	//}
}
function fnShrinkPic() {
    growImg.width= img_width + "px";
	growImg.height= img_height +"px";
	document.getElementById('divPic').style.width= 124 +"px";
	document.getElementById('divPic').style.height= 104 +"px";
	document.getElementById('divPic').style.top=310 +"px";
	document.getElementById('divPic').style.left=368 +"px";
	document.getElementById('lblPart').style.top=1 +"px";
    document.getElementById('lblPart').style.left=1 +"px";
    document.getElementById('lblPart').style.height=18 +"px";
    document.getElementById('lblPart').style.width=120 +"px";
	  
}

function strReplaceAll(str,strFind,strReplace) {
	var returnStr = str;
	var start = returnStr.indexOf(strFind);
	while (start>=0)
	{
		returnStr = returnStr.substring(0,start) + strReplace + returnStr.substring(start+strFind.length,returnStr.length);
		start = returnStr.indexOf(strFind,start+strReplace.length);
	}
	return returnStr;
} 

function fnCreateDXObject(dxResult){
    os = new Array();
    dxr = dxResult.split("~|");
    dxf = dxr[0].split("~_");
    for (currentLne=0; currentLne<dxr.length-1; currentLne++){ 
        var o = new Object();
       
        dxc = dxr[currentLne+1].split("~_");
        //RecordCount
        o["Recordcount"]=dxf[0];
        //Fields
        for (c=1; c< dxc.length ; c++){
                o[dxf[c]]=dxc[c];
        }
        os[currentLne]=o;
    }
    var o = new Object();
    o.rowcount=dxr.length-1;
    o.colcount=dxf.length-1;
    o.row=os;
    return o;
}

function fnVal(value) {
   if ( typeof value == 'undefined') {
        return 0;
   }
   if (value == 'undefined') {
        return 0;
   }
    value=value.toString();
    if (value.substring(0,1)=='$') {
        value=value.substring(1,20);
    } 
    v=parseFloat(value);
     if (isNaN(v)) { v=0}
    return v; 
}

function fnTrim(sString) {
    while (sString.substring(0,1) == ' ') {
        sString = sString.substring(1, sString.length);
    }
    while (sString.substring(sString.length-1, sString.length) == ' ') {
        sString = sString.substring(0,sString.length-1);
    }
    return sString;
} 

 