// ---------------------------------------------------------------------------------------------------------------
// Script for Eshop.html example
// ---------------------------------------------------------------------------------------------------------------
var LCnt, LPrice, LCode;  // Defines arrays needed only for real e-shop
Grids.CookieExpires = 1;  // Sets TreeGrid cookies to expire after this session

// ---------------------------------------------------------------------------------------------------------------
// TreeGrid event handler
// Changes color of cells for upgrading to red
/*Grids.OnGetColor = function(G,row,col,r,g,b,type) {
if(row.id!='Total' && row.O>0 && !type) b=128;
//if((row.B || col>="I" && col!="S") && col && G.CanEdit(row,col)){ b-=15; g-=15; }
if(r==255 && g==255 && b==255) return "";
return "rgb("+r+","+g+","+b+")";
}*/

// ---------------------------------------------------------------------------------------------------------------
// TreeGrid event handler
// Called after every cell change
// Sets the cell is marked as changed only if contains not null value
// Also re-generates the report 
Grids.OnValueChanged = function(G,row,col,val) {
var P = ["B","P","S","G"];
if(val<0) val = 0;
if(row.id=="CW" && val>1000) val = 1000;
if(row.id=="OP" && val>=100000) val = 99999;
var z = row[col]; row[col] = val;
var nl = 1;
if(row.id=='SCE'||row.id=='CW'||row.id=='OP') nl =  !row.SP;
else if(row.id=='ES') nl = !row.P && !row.G;
else if(row.id=='UPG') {
   row.Ver = 0;
   if(row.P) {
      G.ShowMessage("Validating code ...");
      AjaxCall({Url:"Get.aspx",Method:"Post",Param:{Get:"GetVer.aspx",RCode:row.P}},null,function(code,res){
         row.Ver = res;
         UpdateOrder();
         G.HideMessage();
         if(!(res>0 || res=="ALL")) alert("Unknown serial code");
         });
      }
   nl = !row.P;
   }
else { 
   nl = !row.B && !row.P && !row.S && !row.G;
   if(val){ // vymaze vsechny ostatni 
      for(var r=G.GetFirst();r;r=G.GetNext(r)){
         if(!r.Changed) continue;
         var c =  r.id.charAt(0);
         if(c!='T' && c!='P') continue;
         for(var i=0;i<4;i++) {
            if(r[P[i]] && (row!=r||P[i]!=col)){
               G.SetValue(r,P[i],0,1);
               if(r!=row) r.Changed = false;
               G.Recalculate(r,P[i]);
               G.ColorRow(r);
               }
            }
         }
      }
   }
row.Changed=nl?0:1;
G.Recalculate(row,col,1);
UpdateOrder();
if(!nl) row[col] = z;
G.ColorRow(row);   
G.SaveCfg();
return val;
}

// ---------------------------------------------------------------------------------------------------------------
// TreeGrid event handler
// Called after grid finished rendering
// Re-generates report for the first time - if grid loaded its state and values from cookies
Grids.OnRenderFinish = function(G){
UpdateOrder();
}

// ---------------------------------------------------------------------------------------------------------------
// Main function to generate report
function UpdateOrder(){
CalcSupport();
var G = Grids[0];
var F = G.GetRowById("Results"); // Gets the row to display there the report

var A = new Array(),a=0;
var D = [["B","BASIC"],["P","PERSONAL"],["S","STANDARD"],["G","GRAND"]];

// --- Iterates all variable rows and checks if the appropriate cells contain value
for(var r=G.GetFirst();r;r=G.GetNext(r)){
	if(r.id=='UPG') continue; // upgrades
	if(r.id=='SCE'){ // Source code escrow
		var x = new Object();
      x.Count = r.SP;
      x.Price = 250*x.Count;
      x.Name = "Source code escrow";//r.I + " " + G.GetString(r,"S").replace(/DIV/g,"I");
      x.Id = r.id;
      if(x.Count) A[a++] = x;
		}
   else if(r.id=='ES'){ // Extened support
		var x = new Object();
      x.Count = 1;
      x.Price = r.O;
      if(r.GP==r.O) { // Hazi to vzdy r.G, kdo vi proc
         x.Id = "ESA";
         x.Name = "Extended support for whole product lifetime of ";
         }
      else { 
         x.Id = "ES";
         x.Name = "Extended support of ";
         }
      var upg = G.GetRowById("UPG");
      if(upg.P){ // upgrade
         var rr = GetRowCode(upg.P);
         if(!rr) x.Price = 0; // toto by nastat nemelo
         else {
            x.Name += rr.I;
            var c = upg.P.charAt(0).toUpperCase();
            for(var i=0;i<4;i++) if(D[i][0] == c) x.Name+=" <B>"+D[i][1]+"</B>";
            }
         }            
   
      if(x.Price) A[a++] = x;
		}		
   else if(r.id=="CW"){ // custom work
      var x = new Object();
      x.Count = r.SP;
      x.Price = 55*x.Count;
      x.Name = "custom work";
      x.Id = r.id;
      if(x.Count) A[a++] = x;
      }
   else if(r.id=="OP"){ // other payment
      var x = new Object();
      x.Count = 1;
      x.Price = r.SP;
      x.Name = "other payment";
      x.Id = r.id;
      if(x.Price) A[a++] = x;
      }      
   else for(var i=0;i<4;i++){ // normal license or support
		var o = D[i][0], p = o+"P";
      if(r[o]){
         var x = new Object();
         A[a++] = x;
         var id = r.id.split("_");
         if(r.id=='ES' || r.id=='ESA'){ 
            x.Id = id[0];
				x.Name = (r.id=='ES' ? "Extended support for " : "Extended support for whole lifetime of ") + G.GetString(r,"I2")+" <B>"+D[i][1]+"</B>";
				}
         else {
            x.Id = o+id[0];
            x.Name = r.I+" <B>"+D[i][1]+"</B>";
            }
         x.Count = r[o];
         x.Col = o;
         x.Row = r;
         
         if(id[1]){ // extended support
				var y = new Object();
				A[a++] = y;
				y.Count = x.Count;
				if(id[1]==1){ // one year
					y.Id = "ES";
					y.Name = "Extended support of "+x.Name;
					y.Price = r[p]*x.Count/12*2;
					x.Price = r[p]*x.Count/12*10;
					}
				else { // whole lifetime
					y.Id = "ESA";
					y.Name = "Extended support for whole lifetime of "+x.Name;
					y.Price = r[p]*x.Count/16*6;
					x.Price = r[p]*x.Count/16*10;
					}
				}
			else x.Price = r[p]*x.Count;	
         }
      }
   } 

// --- Creates the report text ---
F.BP = "";

// --- Upgrade ---
var U = G.GetRowById('UPG'), c = null, vupg = 0;
G.SetValue(U,"O",0,1);
if(U.P){
   var code = (U.P+"").toUpperCase();
   var r = GetRowCode(code);
   var v = U.Ver;
   if(r) {
      var cc = code.charAt(0);
      for(var i=0;i<4;i++) if(D[i][0] == cc){
         if(v=="ALL" || v>0) {   
            c = r[cc+"P"];
	         if(v==5) { vupg = c *0.4; v = v+".x"; } // za upgrade z 5.x verze na 6.0 zaplati 40%
	         else if(v<5) { vupg = c *0.6; v = v+".x"; } // za upgrade verze zaplati 60%
	         else v = "";
            F.BP += "<BR><I>You declare you have already purchased this component:</I><BR>";
	         F.BP += "&nbsp;&nbsp;&nbsp;<SPAN style='color:red;'>"+G.GetString(r,"I")+" <B>"+D[i][1]+"</B>&nbsp;"+v+"</SPAN><BR>";
	         
	         }
	      else { // chybna verze
            F.BP += "<BR><I style='color:red;'>Unknown serial code to upgrade</I><BR>";
            }
         break;
         }
		}
	}
	
//if(a==1 && A[0].Id=="SCE") a=0; // rusi uplne prazdne source escrow

if(a){
   LCnt = new Object(); LPrice = new Object(); LCode = new Object();
   F.BP+=F.BP ? "<HR>" : "<BR>";
   F.BP += "<B>Your order:</B><BR>";
   for(var i=0;i<A.length;i++){
      if(A[i]){ 
         var mult = "x", pric = 0;
         if(A[i].Id=="ES" || A[i].Id=="SCE") mult = A[i].Count==1 ? " year of" : " years of";
         else if(A[i].Id=="ESA"); // nic
         else if(A[i].Id=="OP") mult = " as ";
         else if(A[i].Id=="CW") mult = A[i].Count==1 ? " hour of" : " hours of";
         else if(c){ // licence upgrade
            pric = A[i].Price - (A[i].Price - c)*(window.UpgAdd?UpgAdd:1.25) - vupg;
            if(pric<=0) {
               F.BP += "&nbsp;&nbsp;&nbsp;<SPAN style='color:red;'>Upgrading would be inconvenient!</SPAN><BR>";
               pric = 0;
               }
            else if(c > A[i].Price){
               F.BP += "&nbsp;&nbsp;&nbsp;<SPAN style='color:red;'>Cannot upgrade to selected product!</SPAN><BR>";
               pric = 0;
               }
            else { 
               G.SetValue(U,"O",-pric,1);
               }
				/*if(A[i].Count>1){ // More counts for one upgrade, divides it
					var P = new Object();
					for(var x in A[i]) P[x] = A[i][x];
					A[i].Price = A[i].Price / A[i].Count;
					A[A.length] = P;
					P.Count = A[i].Count-1;
					P.Price = A[i].Price*P.Count;
					A[i].Count = 1;
					}
				var pric = 0;
				var r = G.GetRowById(A[i].Id.slice(1));
				if(U.I2<=7){ // Upgrade from previous
					pric+=U[c+"P"]*0.4;
					}
				var dp = r[c+"P"] - U[c+"P"];
				if(dp<0){ // ### error
					F.BP += "&nbsp;&nbsp;&nbsp;<SPAN style='color:red;'>Cannot upgrade to selected product!</SPAN><BR>";
					}
				else {
					pric+=dp*1.25;
					var dp = r[A[i].Col+"P"] - r[c+"P"];
					if(dp<0 || dp==0 && A[i].Col!=c || A[i].Col=='P' && c=='S'){ // ### error
						F.BP += "&nbsp;&nbsp;&nbsp;<SPAN style='color:red;'>Cannot upgrade to selected license type!</SPAN><BR>";
						}
					else {
						pric+=dp*1.25;
						if(A[i].Price<=pric || pric<=0){ // ### useless
							F.BP += "&nbsp;&nbsp;&nbsp;<SPAN style='color:red;'>Upgrading would be inconvenient!</SPAN><BR>";	
							}
						else { 
							G.SetValue(U,"O",pric - A[i].Price,1);
							A[i].Price = pric;
							c="";
							}
						}
					}*/
				}
         if(A[i].Price-pric>0){
            F.BP += "&nbsp;&nbsp;&nbsp;<SPAN style='color:blue;'><B>"+(A[i].Id=="OP"?"$"+A[i].Price:A[i].Count)+ "</B>"+mult+" "+A[i].Name+"</SPAN><BR>";
            if(!LCnt[A[i].Id]) LCnt[A[i].Id] = A[i].Count;
            else LCnt[A[i].Id] += A[i].Count;
            if(!LPrice[A[i].Id]) LPrice[A[i].Id] = A[i].Price-pric;
            else LPrice[A[i].Id] += A[i].Price-pric;
            }
         LCode[A[i].Id] = U.P;
         }
      }
   F.BP += "<HR>";
   F.BP += "Total order price is <B>"+F.O+"</B> USD&nbsp;&nbsp;&nbsp;<BUTTON style='width:150px;' onclick='Submit();'><B style='color:\"green\"'>Purchase this order</B></BUTTON><BR>";
   F.BP += "<BR>"; 
   }
else F.BP = "<I>No order yet</I>";
F.B = a;

G.RefreshRow(F);   // refreshes the row 
G.SetScrollBars(); // updates the grid size when report changed
}

// ---------------------------------------------------------------------------------------------------------------
// Function called when calculating from formula in XML data
function AddYear(y){
var d=new Date(); 
d.setFullYear(d.getFullYear()+y); 
return d.getTime();
}
// ---------------------------------------------------------------------------------------------------------------
// Vraci radku ke ktere se vaze dany kod
function GetRowCode(code){
var G = Grids[0];
var c = (code+"").toUpperCase();
var s = c.slice(1,3);
switch(c.charAt(1)){
   case "T": s = "TG"; break;
   case "G": s = "PG"; break;
   case "P": s = "PT"; break;
   }
s += c.charAt(3);      
return G.GetRowById(s);
}
// ---------------------------------------------------------------------------------------------------------------
// Calculates price of support according to selected licence
function CalcSupport(){
var G = Grids[0];
var upg = G.GetRowById("UPG");
var res = G.GetRowById("Results");

// --- extended support ---
var es = G.GetRowById("ES");
if(upg.P && upg.Ver==6){ // upgrade

   // --- zjisti zda neni vybrana nejaka licence ---
   for(var r=G.GetFirst();r;r=G.GetNext(r)){
      var id = r.id.slice(0,2);
      if(id=="TG" || id=="PT" || id=="PG"){
         for(var i=0;i<4;i++){
            if(r["BPSG".charAt(i)]) { id="XX"; break; }
            }
         }
      if(id=="XX") break;
      }
   if(id=="XX") {
      es.BP = "<i>Extended support cannot be renewed when upgrading licence</i>";
      es.BPSpan = 8;
      }
   else {   
      var r = GetRowCode(upg.P);
      if(!r) return 0;
      var c = (upg.P+"").toUpperCase();
      s = r[c.charAt(0)+"P"];
      if(!s) return;   
      s = (s-0)/5;
      es.PP = s;
      es.GP = s*3;
      es.BP = "Add one year";
      es.BPSpan = 2;
      es.P = 0;
      es.G = 0;
      }
   }
else {
   if(upg.P) es.BP = "<i>For your license cannot be renewed extended support, please upgrade</i>";
   else es.BP = "<i>To renew extended support please fill your serial code above</i>";
   es.BPSpan = 8;
   }
G.RefreshRow(es);

// --- source code escrow ---
var sce = G.GetRowById("SCE");
if(upg.P || res.O){
   sce.BP = "For all licenses $<B>250</B> per year";
   sce.BPSpan = 4;
   }
else {
   sce.BP = "<i>To purchase or renew source code escrow select new license or fill your serial code above</i>";
   sce.BPSpan = 8;
   }
G.RefreshRow(sce);   

}
// ---------------------------------------------------------------------------------------------------------------
var L = new Object();
L.BPGS = "300085978";
L.BPGE = "300086107";
L.PPGS = "300116634";
L.PPGE = "300116635";
L.GPGS = "300086106";
L.GPGE = "300086110";
L.SPGS = "300086105";
L.SPGE = "300086108";

L.BPTS = "300086111";
L.BPTE = "300086112";
L.PPTS = "300116637";
L.PPTE = "300116638";
L.GPTS = "300086117";
L.GPTE = "300086114";
L.SPTS = "300086115";
L.SPTE = "300086116";

L.BTGS = "300086118";
L.BTGE = "300086119";
L.PTGS = "300116640";
L.PTGE = "300116641";
L.GTGS = "300086120";
L.GTGE = "300086121";
L.STGS = "300086122";
L.STGE = "300086123";

L.STGC = "300086125";
L.GTGC = "300086126";

L.ES = "300086127";
L.ESA = "300165110";
L.SCE = "300094702";
L.CW = "300094700";
L.OP = "300167080";

// ---------------------------------------------------------------------------------------------------------------
function Submit(){
var F = document.createElement("form");
document.body.appendChild(F);
F.action = "https://secure.shareit.com/shareit/checkout.html";
F.method = "post";
F.target = "_top";
var s="<INPUT TYPE=hidden NAME=pc VALUE=c0xhu>";
s+="<INPUT TYPE=hidden NAME=sessionid VALUE=434276165>";
s+="<INPUT TYPE=hidden NAME=random VALUE=2159795e8f0b8086604700471c5914bd>";
for(var c in LCnt){
   if(LCnt[c]){
      s+="<INPUT TYPE=hidden NAME='PRODUCT["+L[c]+"]' VALUE="+LCnt[c]+">";
      s+="<INPUT TYPE=hidden NAME='PRODUCTPRICE["+L[c]+"]' VALUE='"+(LPrice[c]/LCnt[c]*(window.Dsc?Dsc:1))+"USD'>";
      }
   if(LCode[c]) s+="<INPUT TYPE=hidden NAME='HADDITIONAL1["+L[c]+"]' VALUE='"+(LCode[c])+"'>";
   }
F.innerHTML = s;
F.submit();
}
// ---------------------------------------------------------------------------------------------------------------
