//ekran : 1 - maclistesi.jsp
var MAX_COUPON_AMOUNT=1000;

  FOOTBALL_EVENTS = 1;
  BASKETBALL_EVENTS = 2;
  TENIS_EVENTS = 3;
  F1_EVENTS = 4;
  MOTOGP_EVENTS = 5;
  VOLLEYBALL_EVENTS = 6;
  WRC_EVENTS = 7;
  BILLIARD_EVENTS = 8;
  SUPER_SPORT_EVENTS = 9;
  FOOTBALL_SPECIAL_EVENTS = 19;
  BASKETBALL_SPECIAL_EVENTS = 10;
  ATLETISM_EVENTS = 14;
  HENTBOL_EVENTS = 15;
  SPECIAL_EVENTS = 11;
  ANTEPOST_EVENTS = 12;
  FOOTBALL_ANTEPOST_EVENTS = 112;
  BASKETBALL_ANTEPOST_EVENTS = 212;
  UNUSED_EVENT_TYPE = -1;
  ALL_OTHER_EVENTS = 13;
  HANDBALL_EVENTS = 15;
  STATUS_CANCELLED = 2;
  START_CBS_EVALUATION = 2;
  STATUS_PAYABLE = 6;
  START_BILYONER_EVALUATION = 1;
  STATUS_ACTIVE = 0;
  NO_WINNING = -1;
    
  function isEventTypeFootball(eventType) {
		return eventType == FOOTBALL_EVENTS
			|| eventType == FOOTBALL_ANTEPOST_EVENTS
			|| eventType == FOOTBALL_SPECIAL_EVENTS;
	}
	function isEventTypeBasketball(eventType) {
		return eventType == BASKETBALL_EVENTS
			|| eventType == BASKETBALL_ANTEPOST_EVENTS
			|| eventType == BASKETBALL_SPECIAL_EVENTS;
	}
	function isEventTypeSpecial(eventType) {
		return eventType == TENIS_EVENTS
			|| eventType == F1_EVENTS
			|| eventType == MOTOGP_EVENTS
			|| eventType == WRC_EVENTS
			|| eventType == BILLIARD_EVENTS
			|| eventType == SUPER_SPORT_EVENTS
			|| eventType == FOOTBALL_SPECIAL_EVENTS
			|| eventType == BASKETBALL_SPECIAL_EVENTS
			|| eventType == ATLETISM_EVENTS
			|| eventType == SPECIAL_EVENTS;
	}
	function isEventTypeAntepost(eventType) {
		return eventType == ANTEPOST_EVENTS
			|| eventType == FOOTBALL_ANTEPOST_EVENTS
			|| eventType == BASKETBALL_ANTEPOST_EVENTS;
	}
	function isEventTypeSpecialOrAntepost(eventType) {
		return isEventTypeSpecial(eventType) || isEventTypeAntepost(eventType);
	}

  Array.prototype.indexOf = function(obj){
   for(var i=0,len=this.length; i<len; i++){
    if(this[i]==obj){
     return i;
    }
   }
   return -1;
  }

function getMaclistesi(){
    var maclar=new Array();
    try{
        maclar =Maclar;
    }catch(e){
       maclar=parent.Maclar;
    }finally{
       return maclar;
    }

}
function setMaclistesi(maclistesi){
    try{
        Maclar =maclistesi;
    }catch(e){
        parent.Maclar=maclistesi;
    }
}


function getPreviousValidCombinations(){
    var combinaitons=new Array();
    try{
        combinaitons =Combinations;
    }catch(e){
      combinaitons =parent.Combinations;
    }finally{
       return combinaitons;
    }
}

function getSistemler(){
    var result=new Array();
    try{
        result =ValidSistemler;
    }catch(e){
      result =parent.ValidSistemler;
    }finally{
       return result;
    }
}
function setSistemler(sistemler){
    try{
        ValidSistemler =sistemler;
    }catch(e){
        parent.ValidSistemler=sistemler;
    }
}


function InitializeAll(){
    Combinations=new Array();
    Sistem=new Array();
   var maclistesi=getMaclistesi();
    var tbl = document.getElementById('couponTable');
   for (ix=0;ix<tbl.rows.length;ix++){
       tbl.deleteRow(ix);
       ix--;
   }


 for (i=0,len=maclistesi.length;i<len;i++){
     var match=maclistesi[i];
     var matchid=getMatchIdFromMATCHID(match.matchid)
     if (match.eventCode && match.eventCode>0){
         var guesss=match.guess.substr(0,match.guess.indexOf("::"));
         setTimeout("rrftOzelEtkinlik(false,'"+matchid+"','"+match.gameType+"','"+guesss+"','"+match.eventCode+"')",0);
     }else {
         setTimeout("rrft('"+match.eventType+"',false,'"+matchid+"','"+match.gameType+"','"+match.guess+"','genis')",0);

     }
    }
        /*
        var sistemlertable=document.getElementById("sistemlertable");
        for(var i = sistemlertable.rows.length; i > 0;i--)
            {
            sistemlertable.deleteRow(i -1);
        }*/


   setMaclistesi(new Array());
   document.getElementById("kolonCount").value =  "";
   document.getElementById("maxWinAMount").value ="";
   document.getElementById("totalOdds").value = "";
   document.getElementById("couponMoney").value = "";
   document.getElementById("macSayisi").value ="";
   document.getElementById("multiplier").value="2";
if (document.getElementById("KuponAdet"))
        document.getElementById("KuponAdet").value ="1";
    document.getElementById("couponEmptyDiv").style.display ="block";
    document.getElementById("couponDiv").style.display ="none";
    oturumaAta();
}


function rrftOzelEtkinlik(oturum,macKodu,gametype, guess,eventcode,el)
{



    var i = null;
       //secili sistemledern kald?rcaz


    var tbl;
    tbl= document.getElementById('couponTable');
    var convertedMatchCode = getMatchIdFromMATCHID(macKodu);
    var oTr=document.getElementById("tr"+eventcode+"_"+convertedMatchCode);
    if (oTr)
    {
       removeMatchFromTable(tbl,oTr);
    }
    removeMatchByIdAndGuessOZELETKINLIK(macKodu,guess,gametype,eventcode) ;

        var maclistesi=getMaclistesi();
    var bankomaclar=bankoMaclariVer(maclistesi);
    var nonbankomaclar=NonBankoMaclariVer(maclistesi);
    var matchcount=getUniqueMatchCount(maclistesi);
    var bankocount=getUniqueMatchCount(bankomaclar);
    var secilisistemler=Sistemler;

    if (secilisistemler[0]>matchcount-bankocount)
        document.myForm.combinations[secilisistemler].checked=false;
    //Simdi de maclistesindeki kismi temizliyoz.
    var framexx=document.getElementById("maclistesi");
        var doc = null;
        if(framexx.contentDocument)
           doc = framexx.contentDocument;
        else if(framexx.contentWindow)
           // Internet Explorer
           doc = framexx.contentWindow.document;
        else
           doc = framexx.document;

  if (el){
        el.parentNode.setAttribute("bgColor","#e8e8e8");
    }else{
      var tercihtd;
        if (doc){
            tercihtd=doc.getElementById(convertedMatchCode+"_"+eventcode+"_"+gametype+"_"+guess);
            }
        else{
            tercihtd=framexx.document.getElementById(convertedMatchCode+"_"+eventcode+"_"+gametype+"_"+guess);
        }
                 if (tercihtd){
                    tercihtd.setAttribute("bgColor","#e8e8e8");
            }
  }
 if (maclistesi.length==0){
         document.getElementById("couponEmptyDiv").style.display ="block";
         document.getElementById("couponDiv").style.display ="none";

      }

  if (oturum)
     hesapla();



}

function rrftMultiple(eventType,oturum,macKodu,gametype,genismi)
{


    var i = null;
       //secili sistemledern kald?rcaz
    var maclistesi=getMaclistesi();
    var bankomaclar=bankoMaclariVer(maclistesi);
    var nonbankomaclar=NonBankoMaclariVer(maclistesi);
    var matchcount=getUniqueMatchCount(maclistesi);
    var bankocount=getUniqueMatchCount(bankomaclar);
    var secilisistemler=Sistemler;


    var counter =0;
    for (i=0;i<maclistesi.length;i++){
        var dublematches=maclistesi[i];
        if (dublematches.matchid==macKodu){
                rrft(eventType,false,macKodu, dublematches.gameType,dublematches.guess,genismi)  ;
        }
    }



    //Simdi de maclistesindeki kismi temizliyoz.
 if (maclistesi.length==0){
        document.getElementById("couponEmptyDiv").style.display ="block";
         document.getElementById("couponDiv").style.display ="none";

      }

     if (oturum)
       hesapla();
}



function rrft(eventType,oturum,macKodu,gametype, guess,genismi,el)
{

var tempMathcCodu=macKodu;
macKodu=getMatchIdFromMATCHID(macKodu);


    var i = null;
       //secili sistemledern kald?rcaz


    var tbl= document.getElementById('couponTable');
    var oTr=document.getElementById("tr"+macKodu);


   if (gametype=='SF'){
           var rowssss=tbl.rows;
            for (i=0;i<rowssss.length;i++){
                 if (rowssss[i].getAttribute("id")=="tr"+macKodu){
                     var alltds=rowssss[i].getElementsByTagName("strong");
                        if  (alltds[1].getAttribute("id")=='tercih'+macKodu && alltds[1].innerHTML==guess){
                               oTr=rowssss[i];
                             }
                     }
                 }
            }


    if (oTr)
    {
       removeMatchFromTable(tbl,oTr);
    }

    removeMatchByIdAndGuess(tempMathcCodu,guess,gametype) ;

        var maclistesi=getMaclistesi();
    var bankomaclar=bankoMaclariVer(maclistesi);
    var nonbankomaclar=NonBankoMaclariVer(maclistesi);
    var matchcount=getUniqueMatchCount(maclistesi);
    var bankocount=getUniqueMatchCount(bankomaclar);
    var secilisistemler=Sistemler;


    if (secilisistemler[0]>matchcount-bankocount){
           if(document.myForm.combinations[secilisistemler])
                document.myForm.combinations[secilisistemler].checked=false;
    }
    //Simdi de maclistesindeki kismi temizliyoz.
    var framexx=document.getElementById("maclistesi");
       var doc = null;
        if(framexx.contentDocument)
           doc = framexx.contentDocument;
        else if(framexx.contentWindow)
           // Internet Explorer
           doc = framexx.contentWindow.document;
        else
           doc = framexx.document;

if (genismi=='detay'){

    if (el){
        el.parentNode.setAttribute("bgColor","#f2f7e6");
    }
    //Genis ekrandakinden de kaldï¿½rcaz
             framexx=document.getElementById('maclistesi');
               var tercihtd=doc.getElementById(macKodu+"_"+gametype+"_"+guess);
              if (tercihtd){
                              var index=tercihtd.cellIndex;
                                if (eventType!=BASKETBALL_EVENTS){
                                          if ((index==6||index==8||index==10 ||index==16||index==18|| index==20 )&& (gametype=='F'|| gametype=='S' ))
                                                    tercihtd.setAttribute("bgColor","#e8e8e8");
                                          else
                                                    tercihtd.setAttribute("bgColor","#f2f7e6");
                                 }else if (eventType==BASKETBALL_EVENTS){
                                        tercihtd.setAttribute("bgColor","#f2f7e6");
                                 }
                          }else {
                                //Table i veya table rwou boyuyoz.
                              var matchindex=getMatchByMatchId(maclistesi,macKodu,gametype);
                               if (!matchindex || matchindex.length==0){
                                     var trx=doc.getElementById("tr_row"+(macKodu));
                                        var tr_table =doc.getElementById("tr_table"+(macKodu));

                                         var myframeName;
                                   if (framexx.location)
                                        myframeName=framexx.location.href;
                                   else if (framexx.src)
                                        myframeName=framexx.src;

                                        var currentEventType=1;
                                        var currentgameType="";
                                        if (myframeName.indexOf("eventType")>-1){
                                            currentEventType=myframeName.substring(myframeName.indexOf("eventType")+10,myframeName.indexOf("eventType")+11);
                                        }
                                        if (myframeName.indexOf("gameType")>-1){
                                            var newsrc=myframeName.substring(myframeName.indexOf("gameType")+9,myframeName.length);
                                            currentgameType=newsrc.substring(0,newsrc.indexOf("&"));
                                        }

                                        if (trx)
                                            {
                                                var cells =trx.cells;
                                                  var starttd=0;
                                                    var endtd=cells.length;
                                                    if (currentEventType==1 && currentgameType=='SF'){
                                                        starttd=6;
                                                        endtd=cells.length-1;
                                                    }else if (currentEventType==1 && currentgameType==''){
                                                        starttd=6;
                                                        endtd=cells.length-1;
                                                    }else if (currentEventType==1 && currentgameType=='GS'){
                                                        starttd=6;
                                                        endtd=cells.length-1;
                                                    }else if (currentEventType==2 && currentgameType=='SF'){
                                                        starttd=10;
                                                    }else if (currentEventType==2 && currentgameType==''){
                                                        starttd=6;
                                                    }
                                            for (kl=starttd;kl<endtd;kl++){
                                                    var tempColor="#f2f7e6";
                                                    if (currentEventType==1 && currentgameType=='' && (kl==6||kl==8||kl==10 || kl==16||kl==18|| kl==20)){
                                                        tempColor="#e8e8e8";
                                                    }
                                                     //Burda Olabilecek Rengi Seccez.
                                                    cells[kl].setAttribute("bgColor",tempColor);
                                                }
                                            }
                                     if (tr_table){//Table i, kaldırcaz.
                                           tr_table.setAttribute("bgColor","#F7F7F7");
                                             for (ik=0;ik<tr_table.rows.length;ik++){
                                             var trtablerow=tr_table.rows[ik];
                                             trtablerow.setAttribute("bgColor","#F7F7F7");
                                             var trtableRowCells=trtablerow.cells;
                                             for (jk=0;jk<trtableRowCells.length;jk++){
                                                 trtableRowCells[jk].setAttribute("bgColor","#F7F7F7");
                                             }

                                         }
                                        }
                               }
                           }



  }else{
     //Table i veya table rwou boyuyoz.
        var tercihtd=doc.getElementById(macKodu+"_"+gametype+"_"+guess);
        if (genismi=='genis'){
                 if (tercihtd){
                    var index=tercihtd.cellIndex;
                     if (eventType==FOOTBALL_EVENTS){
                              if ((index==6||index==8||index==10 ||index==16||index==18|| index==20 )&& (gametype=='F'|| gametype=='S' ))
                                        tercihtd.setAttribute("bgColor","#e8e8e8");
                              else   {
                                                tercihtd.setAttribute("bgColor","#f2f7e6");

                              }

                     }
                     else if (VOLLEYBALL_EVENTS || BASKETBALL_EVENTS){
                            tercihtd.setAttribute("bgColor","#f2f7e6");
                     }
                }else {//Tum secili satırları kaldırıyoz.
                        var matchindex=getMatchByMatchId(maclistesi,macKodu,gametype);
                     if (!matchindex || matchindex.length==0){
                              var matchindex=getMatchByMatchId(maclistesi,macKodu,gametype);
                                     var trx=doc.getElementById("tr_row"+(macKodu));
                                        var tr_table =doc.getElementById("tr_table"+(macKodu));

                                     var myframeName;
                                         if(framexx.contentDocument)
                                                {
                                                    myframeName=framexx.contentDocument.location.href;;
                                                }
                                        else if(framexx.contentWindow){
                                              myframeName=framexx.contentWindow.location.href;;
                                         }

                                        var currentEventType=1;
                                        var currentgameType="";
                                        if (myframeName.indexOf("eventType")>-1){
                                            currentEventType=myframeName.substring(myframeName.indexOf("eventType")+10,myframeName.indexOf("eventType")+11);
                                        }
                                        if (myframeName.indexOf("gameType")>-1){
                                            var newsrc=myframeName.substring(myframeName.indexOf("gameType")+9,myframeName.length);
                                            currentgameType=newsrc.substring(0,newsrc.indexOf("&"));
                                        }

                                        if (trx)
                                            {
                                                var cells =trx.cells;
                                                  var starttd=0;
                                                    var endtd=cells.length;
                                                    if (currentEventType==1 && currentgameType=='SF'){
                                                        starttd=6;
                                                        endtd=cells.length-1;
                                                    }else if (currentEventType==1 && currentgameType==''){
                                                        starttd=6;
                                                        endtd=cells.length-1;
                                                    }else if (currentEventType==1 && currentgameType=='GS'){
                                                        starttd=6;
                                                        endtd=cells.length-1;
                                                    }else if (currentEventType==2 && currentgameType=='SF'){
                                                        starttd=10;
                                                    }else if (currentEventType==2 && currentgameType==''){
                                                        starttd=6;
                                                    }
                                            for (kl=starttd;kl<endtd;kl++){
                                                    var tempColor="#f2f7e6";
                                                    if (currentEventType==1 && currentgameType=='' && (kl==6||kl==8||kl==10 || kl==16||kl==18|| kl==20)){
                                                        tempColor="#e8e8e8";
                                                    }
                                                     //Burda Olabilecek Rengi Seccez.
                                                    cells[kl].setAttribute("bgColor",tempColor);
                                                }
                                            }
                                     if (tr_table){//Table i, kaldırcaz.
                                         tr_table.setAttribute("bgColor","#F7F7F7");
                                         for (ik=0;ik<tr_table.rows.length;ik++){
                                             var trtablerow=tr_table.rows[ik];
                                             trtablerow.setAttribute("bgColor","#F7F7F7");
                                             var trtableRowCells=trtablerow.cells;
                                             for (jk=0;jk<trtableRowCells.length;jk++){
                                                 trtableRowCells[jk].setAttribute("bgColor","#F7F7F7");
                                             }

                                         }
                                        }

                     }
                 }
            }
    }


    if (gametype=='SF')
        {
            iYMSleriEnableEt(getMaclistesi(),macKodu);
        }

 setMaclistesi(maclistesi);

if (oturum)
     hesapla();

}

/**
 * Tablo uzerinde oynayÃ„Â±nca burasÃ„Â± calÃ„Â±sÃ„Â±yor.Mac listesi ÃƒÂ¼zerindeki bir orana tÃ„Â±klandÃ„Â±Ã„ÂŸÃ„Â±nda kupondan kaldÃ„Â±rÃ„Â±yoruz.
 * @param genismi
 * @param macKodu
 * @param index
 */

//**Trim ()
function ltrim(str) {
	for(var k = 0; k < str.length && isWhitespace(str.charAt(k)); k++);
	return str.substring(k, str.length);
}
function rtrim(str) {
	for(var j=str.length-1; j>=0 && isWhitespace(str.charAt(j)) ; j--) ;
	return str.substring(0,j+1);
}
function trim(str) {
	return ltrim(rtrim(str));
}
function isWhitespace(charToCheck) {
	var whitespaceChars = " \t\n\r\f";
	return (whitespaceChars.indexOf(charToCheck) != -1);
}



function removeMatchByIdAndGuess(matchid,tercih,gametype){
var secilenMac=getMaclistesi();
var result=new Array();
var deletematchid=matchid;

for (i=0;i<secilenMac.length;i++)
       {
            if (!(deletematchid==secilenMac[i].matchid && tercih ==secilenMac[i].guess ))
                {
                    result.push(secilenMac[i]);
                }
        }
  setMaclistesi(result);
}


function removeMatchByIdAndGuessOZELETKINLIK(matchid,tercih,gametype,eventCode){
var secilenMac=getMaclistesi();
var result=new Array();



for (i=0;i<secilenMac.length;i++)
       {
            if ((matchid!=secilenMac[i].matchid ))
                {
                  var tempGuess=secilenMac[i].guess;
                  if (secilenMac.eventCode && secilenMac[i].eventCode>0)
                        tempGuess=tempGuess.substr(tempGuess.indexOf("::"),tempGuess.length);
                   if ( tercih !=tempGuess )
                        result.push(secilenMac[i]);
                }
        }
  setMaclistesi(result);
}



function findIndexOfMatchByMatchId(matchlist,matchid, tercih){
    for (i=0;i<matchlist.length;i++){
        if (matchlist[i].matchid==matchid  && tercih== matchlist[i].guess)
                return i;
    }

    return -1;
}

//Iterate through the hashtable and find the mbs
/* burdaki algoritma simdi sole
   Once turlere gore3 grupluyoz
   sonra mbslere gore veeee buluyoz
  */
function getMbs(maclistesi){
    var tablermbs={"1":0,"2":0,"3":0,"4":0};
     for (ikj=0,leng=maclistesi.length; ikj<leng; ikj++){
             var mac=maclistesi[ikj];
             var mb=mac.mbs;
             tablermbs[mac.mbs]++;       //toplam? bir art?trd?k
     }
//for other combinations  for macsonucu cifet sans and alti ustu
   for(var ixj in tablermbs ){
        if (ixj==2){
           if (tablermbs[4]==0&& tablermbs[3]==0)
                return 2;
       }
       if (ixj==3){
           if (tablermbs[4]==0)
                return 3;
           else
                return 4;
       }
       if (tablermbs[ixj]!=0 && ixj <=tablermbs[ixj])
            return ixj;
   }
  return 4;
}

//Secilebileck sistemleri de set ederek  bs degerini donderiyoruz.
function getMbsForSystems(maclistesi){
    var tablermbs={"1":0,"2":0,"3":0,"4":0};
     for (ikj=0,leng=maclistesi.length; ikj<leng; ikj++){
             var mac=maclistesi[ikj];
             var mb=mac.mbs;
             tablermbs[mac.mbs]++;       //toplam? bir art?trd?k
     }
//for other combinations  for macsonucu cifet sans and alti ustu
   for(var ixj in tablermbs ){
       if (ixj==1){//
           if (tablermbs[1]>0 && tablermbs[2]+tablermbs[3]+tablermbs[4]==1){
               return 2;
           }else if (tablermbs[1]>0 && tablermbs[2]+tablermbs[3]+tablermbs[4]>=2){
              if (tablermbs[1]==1 && tablermbs[2]==1 && tablermbs[3]==1 && tablermbs[4]==1){
                   return 4;
               }
               if (tablermbs[1]==1 && tablermbs[2]==1 && tablermbs[3]==0 && tablermbs[4]>1){
                   return 4;
               }
               if (tablermbs[1]==1 && tablermbs[2]==1 && tablermbs[3]==0 && tablermbs[4]>1){
                   return 4;
               }
               if (tablermbs[2]==2 && tablermbs[3]==0 && tablermbs[4]==0){
                   return 2;
               }
               if ((tablermbs[2]==2 || tablermbs[3]==2) && tablermbs[4]==1){
                   return 4;
               }
               if((tablermbs[1]+tablermbs[2]+tablermbs[3]+tablermbs[4])==3) {
            	   return 3;
               }
           }
       }
       if (ixj==2){
             if (tablermbs[2]>0 && tablermbs[3]+tablermbs[4]==1){
               return 3;
           }
       }
   }
   var mbs=0;
     for (ikj=0,leng=maclistesi.length; ikj<leng; ikj++){
             var mac=maclistesi[ikj];
             if (mac.mbs>mbs)
                mbs=mac.mbs;
     }
     
  return mbs;
}


function getMaxMbs(tablermbs){
    if (tablermbs[4] > 0)
        return 4;
    if (tablermbs[3] > 0)
       return 3;
    if (tablermbs[2] > 0)
        return 2;
    return 1;
}
//Onclikle Match Clas?m?z
function Match(eventType,matchid,banko,gameType,odd,homeTeam,awayTeam,mbs,guess,eventCode){
    if (eventCode)
        matchid+="."+eventCode;
   this.matchid=matchid;
   this.gameType=gameType
   this.odd= odd;
   this.homeTeam= homeTeam
   this.awayTeam= awayTeam
   this.guess =guess;
   this.banko =banko;
   this.mbs=mbs;
   this.eventCode=eventCode;
   this.eventType=eventType;
}

function Combination (maclar,toplamOran,valid){
    this.maclar=maclar;
    this.toplamOran=toplamOran;
    this.valid=valid;
}

function kuponAreaAdd(eventType,macKodu,oran,gameType,MBS,macadi,tercih,banko,eventCode) {
    var maclistesi=getMaclistesi();
   var newbanko=banko;
  var oldmatch;
  var index=-1;


   for (k=0;k<maclistesi.length;k++){
       if (maclistesi[k].matchid==macKodu){
           oldmatch=maclistesi[k];
           index=k;
           newbanko=oldmatch.banko;
           break;
       }
   }


var newmatch=new Match(eventType,macKodu,newbanko,gameType,oran,macadi,macadi,MBS,tercih,eventCode);
if (index>-1 && newmatch.odd>oldmatch.odd){
    maclistesi[index]=newmatch;
    maclistesi.push(oldmatch);
}else {
    maclistesi.push(newmatch);
}
    setMaclistesi(maclistesi);
    hesapla();

 }




//gets only one instance of the match
function bankoMaclariVer(maclistesi){
 var bankomaclar=new Array();
   for (i=0,len=maclistesi.length;i<len;i++){
   var exist=false;
   if (maclistesi[i].banko==1){
       for (ix=0,blen=bankomaclar.length;ix<blen;ix++){
           if (bankomaclar[ix].matchid==maclistesi[i].matchid)
                 exist=true;
           if (exist && isEventTypeSpecialOrAntepost(maclistesi[i].eventType)){
               if (bankomaclar[ix].eventCode!=maclistesi[i].eventCode)
                    exist=false;
           }
       }
       if (!exist)
            bankomaclar[bankomaclar.length]=maclistesi[i];
    }
}
 return bankomaclar;
}

function getSystems(){
 var sistem= new Array();
 if (document.myForm.combinations){
     var allcomb=document.getElementsByName("combinations");
        for (i=0,len=allcomb.length;i<len;i++)    {
            if (allcomb[i] && allcomb[i].checked)
                sistem.push(allcomb[i].value);
        }
    }
    return sistem;
}

function getDoubleMatches(maclistesi){
 var doublematches=new Array();
 for (var i=0,len=maclistesi.length;i<len;i++){
     var match=maclistesi[i];
     var exist=false;
     for (var ix=0,len2=doublematches.length;ix<len2;ix++){
            var oncekiarray=doublematches[ix];
            if (oncekiarray[0].matchid==match.matchid&& oncekiarray[0].gameType==match.gameType)
            {
            oncekiarray.push(match);
            exist=true;
            }
       }
     if (!exist){
         var temparray=new Array();
         temparray.push(match);
         doublematches.push(temparray);
     }
 }

    var returndouyble=new Array();
 for (var i=0,len=doublematches.length;i<len;i++){
     if(doublematches[i].length>1){//Match double ise tekrar insert etcez.
         returndouyble.push(doublematches[i]);
     }
 }
 return returndouyble;
}

//gets only one instance of the match
function NonBankoMaclariVer(maclistesi){
var nonbankomaclar=new Array();
 for (i=0,len=maclistesi.length;i<len;i++){
    if (maclistesi[i].banko==0||maclistesi[i].banko=='undefined'|| !maclistesi[i].banko ){
        var exist=false;
        for (ix=0,len2=nonbankomaclar.length;ix<len2;ix++){
           if (nonbankomaclar[ix].matchid==maclistesi[i].matchid)
                 exist=true;
       }
        if (!exist)
            nonbankomaclar[nonbankomaclar.length]=maclistesi[i];
         }
   }
  return nonbankomaclar;
}


function cloneObject(obj) {
      if(obj == null || typeof(obj) != 'object')
        return obj;

    var temp = new obj.constructor(); // changed (twice)
    for(var key in obj)
    {
        if ( typeof(obj[key])!='function')
            temp[key] = cloneObject(obj[key]);
    }
    return temp;
    }


function findIndexOfMatch(maclistesi,match){
  if (maclistesi){
    for (i=0,len=maclistesi.length;i<len;i++){
        if (maclistesi[i].matchid==match.matchid &&maclistesi[i].odd==match.odd && maclistesi[i].guess==match.guess && maclistesi[i].gameType==match.gameType )
                return i;
    }
  }
 return -1;
}

function getDoubleMatchCountInMatches(matchlist,doublematchlist){
 var doublematchcount=0;
for (i=0;i<doublematchlist.length;i++){
    var id=doublematchlist[i][0].matchid;
    for (k=0;k<matchlist.length;k++){
        if (matchlist[k].matchid==id)
            doublematchcount++;
    }
}
    return doublematchcount;

}

//maytchlistesi icinde ilkyyar?macsonucundan fazlaca varm? onu buluyor.Argumant olarak doublematch in verilmesi gerekiyor.
function isThereIYMSInDoubleMatches(matchlist) {
 var threeColonluIYMSTercih=false;
    for (i=0;i<matchlist.length;i++){
        if (matchlist[i].length>1 && matchlist[i][0].gameType=='SF'){//3 lulerden biri iY/Ms ise
            threeColonluIYMSTercih=true;
        }
    }
    return threeColonluIYMSTercih;
}

function isCombinationValid(maclistesi){
  if (maclistesi && maclistesi.length>0){
    var mbsss=getMbs(maclistesi);
    if (mbsss<=maclistesi.length)
        return true;
  }
    return false;
}


function generateAllValidCombinations (maclistesi,bankomaclar,bankocount,nonbankomaclar,matchcount,secilisistemler){
//maclistesi Array
//Butun olay burda bitiyor.
var doublematches=getDoubleMatches(maclistesi);

var resultindex=0;
var validSistemHashSet =new Array();
var  singlematches=getSingleMatches(maclistesi, doublematches);


var isValid=true;
 //Deafult olarak false yaptÃ„Â±k.Butun sistemler disabled su an .

//---------------------------------------------------------------------------?lk yar? mac sonucu secmisse diger sistemleri disabler ediyoz.
var totalCombinationCountOfSeciliSistemler=0;
if (secilisistemler.indexOf(0)>-1 && secilisistemler.length==1){
    secilisistemler=new Array();
}
if (secilisistemler.length>0){
    var tempsecilisistemler=new Array();
    for (k=0;k<secilisistemler.length;k++){//Bakcaz.Secili sistemlerdeki herbir elemanÄ±n combination sayÄ±sÄ± 1000 den buyukse kaldÄ±rcaz.
         var combcount=getTotalCombinationCount(singlematches,doublematches,secilisistemler[k],bankomaclar);
        if (combcount<MAX_COUPON_AMOUNT&& totalCombinationCountOfSeciliSistemler+combcount<=MAX_COUPON_AMOUNT){
                tempsecilisistemler.push(secilisistemler[k]);
            totalCombinationCountOfSeciliSistemler+=combcount;
        }

    }
    secilisistemler=tempsecilisistemler;
}

var sistemler=cloneObject(secilisistemler);

var iymsvarmi =isThereIYMSInDoubleMatches(doublematches);
if (iymsvarmi){
    for (ik=0;ik<=30;ik++){
        validSistemHashSet[ik]=false;
    }
    bankombs=getMbs(bankomaclar);
    var allmbs=getMbs(singlematches);
    if (bankomaclar.length>=bankombs-1 && bankomaclar.length>=allmbs-1){
        validSistemHashSet[1]=true;
        if (secilisistemler.indexOf(1)<0)
            secilisistemler.push(1);
        sistemler=cloneObject(secilisistemler);
   }
    if (bankomaclar.length>=bankombs && secilisistemler.length>0  ){
        validSistemHashSet[0]=true;
   }

}else {//Ã¯Â¿Â½lk yari mac sonucu coklu secmemiÃ¯Â¿Â½se  Sistemleri hesapliyoruz.
    var mbs=getMbsForSystems(nonbankomaclar);
    var bankombs;
    if (bankocount==0)
        {
            bankombs=0;//UlasÃ¯Â¿Â½lamaz bi mac sayÃ¯Â¿Â½sÃ¯Â¿Â½
        }else {
            bankombs=getMbs(bankomaclar);
        }
      for (var i=0;i<=nonbankomaclar.length;i++){
        var combcount=getTotalCombinationCount(singlematches,doublematches,i,bankomaclar);
          var maxCombinationCount =0;
          if (secilisistemler.indexOf(""+i)==-1)
              {
                maxCombinationCount=  totalCombinationCountOfSeciliSistemler+combcount;
              }
          else {
              maxCombinationCount=  totalCombinationCountOfSeciliSistemler;
            }
          if ( ((bankombs!=0 && bankombs<=bankocount ) || (bankombs!=0 &&  bankombs<=i )
               ||(bankombs!=0 && bankocount+i>=bankombs && i+bankocount>=mbs  )|| (bankombs==0 && i>=mbs) )
                  && combcount<MAX_COUPON_AMOUNT && maxCombinationCount<=MAX_COUPON_AMOUNT){
                    validSistemHashSet[i]=true;
                }
            else {
                validSistemHashSet[i]=false;
                var sistemlerindex=sistemler.indexOf(""+i);
                if (sistemlerindex>-1){
                    sistemler=sistemler.splice(sistemlerindex,1);
                }
            }
        }
    validSistemHashSet[0]=false;
    if (bankombs!=0 && bankombs<=bankocount && secilisistemler.length>0 ){//Sistem 0
        validSistemHashSet[0]=true;
    }
}


//---------------------------------------------------------------------------


    var sonuc=new Array();  //Burda Butun combinasyonlar tutuluyor.
    var resultindex=0;

if (sistemler.length==0){
    var combmaclar=nonbankomaclar.concat(bankomaclar);
    var orann=getCombinationsTotalOdss(combmaclar);
    var iscombvalid=isCombinationValid(combmaclar);
    var ccomb=new Combination( combmaclar, orann,iscombvalid);
    sistemler.push(""+(matchcount-bankocount));
    sonuc.push(ccomb);
}else{
    for (var k in sistemler) {
      //Combs(bankomaclar,nonbankomaclar,bankocount,matchcount,sonuc,sistemler[k],nonbankomaclar, [],sistemler);
     sonuc=sonuc.concat(combine(nonbankomaclar, parseInt(sistemler[k])));
    }
    var tempsonuc=new Array();
    for (i=0;i<sonuc.length;i++){
        if (sonuc[i]&& sonuc[i][0]){
            var bankolumaclar=bankomaclar.concat(sonuc[i]);
             var iscombvalid=isCombinationValid(bankolumaclar);
            var orani=getCombinationsTotalOdss(bankolumaclar);
            tempsonuc.push(new Combination(bankolumaclar,orani,iscombvalid));
        }
    }
    sonuc=tempsonuc;
}
 if (secilisistemler.indexOf(0)>-1){ //Sistem 0 seÃ§miÅŸse Sonuclara onu da ekliyoruz.
    var orann=getCombinationsTotalOdss(bankomaclar);
    var iscombvalid=isCombinationValid(bankomaclar);
    var ccomb=new Combination( bankomaclar, orann,iscombvalid);
     sistemler.push(0);
    sonuc.push(ccomb);
 }

//---------------------------------------------------------------------------
    /**
     *Sonuc duble matchler iÃƒÂ§in tek bir combinasyyon iÃƒÂ§eriyor.Ama yuksek olan oranlÃ„Â± macÃ„Â± iÃƒÂ§eriyor.
     *Toplam Oranda problem yok ama Secilebilir sistemlerde  bir kac problem var.
     */
 if (doublematches.length>0){  //matchid  ve  toplamo0ran seklinde bir aray a atcaz.
        var sonTempsonuc=cloneObject(sonuc);
    /**
     * Sonuctaki herbir eleman iÃ¯Â¿Â½in clone ediyoz.double match sayÃ¯Â¿Â½sÃ¯Â¿Â½nca.
     */
        for (var jk=0;jk<doublematches.length;jk++){//Double mnatch sayÃ¯Â¿Â½sÃ¯Â¿Â½nca sonuc arrayini clone ediyoruz.
            var dublematch=doublematches[jk];
            var anamatch=dublematch[0];
           for (var di=1;di<dublematch.length;di++){ //Herbir dublematch iÃ¯Â¿Â½in bunu yapiyoz.
                    for (var kl=0; kl<sonTempsonuc.length;kl++){//Yeni kolnladÃ¯Â¿Â½k .Temporary olarak.Ã¯Â¿Â½imdi de iÃ¯Â¿Â½eriÃ¯Â¿Â½ini set ediyoz.maclarÃ¯Â¿Â½ oranlarÃ¯Â¿Â½ degiÃ¯Â¿Â½tiriyoz.//sonuctaki o macÃ¯Â¿Â½ iÃ¯Â¿Â½eren herbir kombinasyonu set ediyoz.
                                    var maclar=sonTempsonuc[kl].maclar;
                                    var dublematchindex=findIndexOfMatch(maclar,anamatch);
                                    if (dublematchindex>-1){//Mac varsa Yeni bir kombinasyon yaratÃ¯Â¿Â½p sonTempSonuc'a ekliyoz.
                                            var newclonedComb=cloneObject(sonTempsonuc[kl]);
                                            newclonedComb.maclar[dublematchindex]=dublematch[di];
                                            newclonedComb.toplamOran=(sonTempsonuc[kl].toplamOran/anamatch.odd)*dublematch[di].odd;
                                            sonTempsonuc.push(newclonedComb);
                                    }
                            }
              }//end of herbir duble match deki duble match iÃ¯Â¿Â½in
        }
      sonuc=sonTempsonuc;
}

//Toplam Oranı
var totalOran=0;
 if (sonuc.length==0){
    totalOran=1;
    for (i=0;i<maclistesi.length;i++)
        {
    		totalOran*=maclistesi[i].odd;
         }
}else{
        var MacCodesHash =new Array();

         for (ijx=0,len=sonuc.length;ijx<len;ijx++){
             var maclarx=sonuc[ijx].maclar;
             var macstring="";
             for (ki=0;ki<maclarx.length;ki++)
                macstring+=maclarx[ki].matchid+"_";
             if (MacCodesHash[macstring]){//Var
               if (MacCodesHash[macstring]<sonuc[ijx].toplamOran){
                    totalOran=totalOran+sonuc[ijx].toplamOran-MacCodesHash[macstring];
                    MacCodesHash[macstring]=sonuc[ijx].toplamOran;
                    }
             }else {
                MacCodesHash[macstring]=sonuc[ijx].toplamOran;
               totalOran+=sonuc[ijx].toplamOran;
             }
            }
    }

for (i=0;i<sonuc.length;i++){
    isValid&=sonuc[i].valid;
}


//now we are gonna to calculate the oddss and mbs for each Combination
  var   result=new Array();
    Combinations=sonuc;  // bunu daha sonra tekrar kullancaz.Cifte mac eklenince.
    result['combinations']=sonuc;
    result['combinationssize']=sonuc.length;
    result['totalOran']=totalOran;
    result['sistemler']=validSistemHashSet;
    result['isValid']=isValid;
    result['secilisistemler']=secilisistemler;
    return result;
   }


/**
 * Double Match ve Single Match count lardan o kombinasyonda olusabilcelek kombinasyon sayÃ„Â±sÃ„Â±nÃ„Â± verir
 * @param singlematches
 * @param doublematches
 * @param sistem
 */
function getTotalCombinationCount(singlematches, doublematches,sistem,bankomatches){


var bankocount=bankomatches.length;


 var bankodoubleMatchcount=0;
 var nonBankoDoubleMatches=cloneObject(doublematches);
 var nonBankoSingleMatches=new Array();

 for (i=0;i<bankomatches.length;i++){
     for (j=0;j<nonBankoDoubleMatches.length;j++){
         if  (nonBankoDoubleMatches[j][0].matchid==bankomatches[i].matchid)
            {
                bankodoubleMatchcount++;
                nonBankoDoubleMatches.splice(j,1);
            }
     }
 }
 for (i=0;i<singlematches.length;i++) {
     if (singlematches[i].banko!=1){
         nonBankoSingleMatches.push(singlematches[i])
     }
 }



if (singlematches.length+nonBankoDoubleMatches.length<sistem)
    return 0;

if (singlematches.length+nonBankoDoubleMatches.length==sistem|| (sistem==0&& bankomatches.length>=getMbs(bankomatches) ))
    return 1;



var doubleMatchMultiplier=1;
for (i=0;i<bankodoubleMatchcount;i++)
    doubleMatchMultiplier*=2;



 if (doublematches.length==0)
 {
     if (singlematches.length-bankocount>sistem)
        return doubleMatchMultiplier*CombCount(singlematches.length-bankocount,sistem)
 }


var totalcount=CombCount(nonBankoSingleMatches.length,sistem);

    for (var ki=1;ki<=nonBankoDoubleMatches.length;ki++){
          var tempcompcount=Math.pow(2,ki);
          tempcompcount*=CombCount(nonBankoDoubleMatches.length,ki);
          tempcompcount*=CombCount(nonBankoSingleMatches.length,sistem-ki) ;
         totalcount+=tempcompcount;
    }

totalcount*=doubleMatchMultiplier;

return totalcount;
}



function hesapla() {
var maclistesi=getMaclistesi();
var bankomaclar=bankoMaclariVer(maclistesi);
var nonbankomaclar=NonBankoMaclariVer(maclistesi);
var matchcount=getUniqueMatchCount(maclistesi);
var bankocount=getUniqueMatchCount(bankomaclar);
var secilisistemler=getSystems();




  var validcomb;
  var allsistemcomb;
  var toplamoran=1;

var checkFinished;
do {
    checkFinished = true;
    var result= generateAllValidCombinations(maclistesi,bankomaclar,bankocount,nonbankomaclar,matchcount,secilisistemler);
    validcomb=result['combinations'];

    //bunu beraber ALCAz.
    allsistemcomb=result['sistemler'];
    toplamoran=result['totalOran'];
    secilisistemler=result['secilisistemler'];

    //Sistem seçimleri invalid mi olmuş?
    var temp = new Array();
if (secilisistemler && secilisistemler.size){
    for(var i= 0; i< secilisistemler.size(); i++)
    {
        if (allsistemcomb[secilisistemler[i]]==false) {
            checkFinished = false;
            continue;
        }
        temp.push(secilisistemler[i]);
    }
}

    if(!checkFinished) secilisistemler = temp;
}while(!checkFinished)

//now coming for system Sistems
manageSystems(allsistemcomb,secilisistemler);

var valid=result['isValid'];

//Toplam orani hespliyoz----------------

 if (maclistesi.length==0)
    toplamoran=0;
 var kazanc=toplamoran* document.myForm.multiplier.value;


 //Kazanc 500000 den fazla olamaz.
 if (kazanc>=500000)
    kazanc=500000;

    var kuponadetvalue=1;
    var kuponAdet= document.getElementById("KuponAdet");
   if (kuponAdet){
       kuponadetvalue=kuponAdet.value;
   }


//-------------------------------------
    var colomncount=result['combinationssize'];
if (valid&& validcomb.length>0){
         //Burda bilgileri g?steriyoruz.

           document.getElementById("kolonCount").value = colomncount;
           document.getElementById("maxWinAMount").value =formatValue(kazanc*kuponadetvalue,2) + " TL";
         document.getElementById("totalOdds").value = formatValue(toplamoran,2);
           document.getElementById("couponMoney").value = (colomncount* document.myForm.multiplier.value*kuponadetvalue ) + " TL";
           document.getElementById("macSayisi").value =matchcount;
        }
else {
     if (maclistesi.length==0){
        toplamoran=0;
         document.getElementById("couponEmptyDiv").style.display ="block";
         document.getElementById("couponDiv").style.display ="none";

      }
       document.getElementById("kolonCount").value = colomncount;
       document.getElementById("maxWinAMount").value =formatValue(toplamoran*document.myForm.multiplier.value,2) + " TL";
       document.getElementById("totalOdds").value = formatValue(toplamoran,2);
       document.getElementById("couponMoney").value = "-";
       document.getElementById("macSayisi").value =matchcount;
}
    Combinations=validcomb;
    setSistemler(allsistemcomb);
    Sistemler=secilisistemler;
    //Burda soldaki ma? listesi framinin boyutunu b?y?t.--------------------------------->>>>
    oturumaAta();
}


function getCombinationsTotalOdss(maclistesi){
    var toplamOran=1;
         for (ikj=0,len=maclistesi.length; ikj<len; ikj++){
        	 	 toplamOran *=maclistesi[ikj].odd;
             }
    return toplamOran;
}


   function getUniqueMatchCount(maclistesi)
 {

      var matches=new Array();
 for (var i=0,len=maclistesi.length;i<len;i++){
     var match=maclistesi[i];
     var exist=false;
     for (var ix=0,len2=matches.length;ix<len2;ix++){
            var oncekiarray=matches[ix];
            if (oncekiarray.matchid==match.matchid&& oncekiarray.gameType==match.gameType)
            {
            exist=true;
            }
       }
     if (!exist){
         matches.push(match);
     }
 }
     return matches.length;
 }

function getSingleMatches(maclistesi,doublematches)
 {
    var macset=new Array();
      for (var i=0,len=maclistesi.length;i<len;i++){
          var index=-1;
            for ( var j=0;j<doublematches.length;j++){
                    if (findIndexOfMatch(doublematches[j],maclistesi[i])>-1){
                        index=1;
                        break;
                    }
                }
          if (index<0){
              macset.push(maclistesi[i]);
          }
      }
     return macset;
 }


function manageSystems(sistemler,secilisistemler){
  try{
    var sistemlertable =document.getElementById("sistemlertable");

    var rowcount=0;
    var cellcount=1;
    for (i=0;i<sistemlertable.rows.length;i++ ){
    	var row = sistemlertable.rows[i];
    	for(var j = 0; j < row.cells.length; j++) {
    		var cell = row.cells[j];
    		cell.innerHTML = "";
    	}

      }
    var rowcount=0;
    var cellcount=1;

    for (i=0;i<sistemler.length;i++ ){
          if (sistemler[i]){
             if (cellcount == 11){
                     rowcount+=2;
                     cellcount=1;
                 }
              var cell=sistemlertable.rows[rowcount].cells[cellcount];
              var checked="";

               if (secilisistemler.indexOf(i)>-1)
                    {
                      checked="checked='checked'";
                    }
              cell.innerHTML="<input type=checkbox id='combinations"+i+"'  STYLE=\"margin-left:2px\" onClick=\"hesapla();\" title='Sistem "+i+"' name='combinations' " +checked+" value=\""+i+"\">";
              sistemlertable.rows[rowcount].cells[cellcount+1].innerHTML=""+i;
             cellcount+=2;
          }
      }


  if (cellcount==1){
      document.getElementById("sistemlerContainerTable").style.display="none";
  }else{
      document.getElementById("sistemlerContainerTable").style.display="block";
  }
  }catch(ex){
      alert (ex)
  }
}



//COmbinatiÃ¯Â¿Â½ons
function factdivdiv( n, k1, k2 ) {
   // computes (n! / k1! k2!) for combinations

   // assure k1 >= k2
   if (k1 < k2) { i = k1;  k1 = k2;  k2 = i; }

   if (k1 > n)  t = 0;
   else {
      // accumulate the factors for k2 factorial
      var t=1;
      while (k2 > 1)
         t *= k2--;

      // accumulate the factors from n downto k1
      var t2=1;
      while (n > k1)
         t2 *= n--;

      t = t2 / t;
      }
   return t;
   }

function CombCount( n, r ) {
   // combinations of n things taken r at a time, order not impt.
   //    Comb( n, 0 ) = 1, and Comb( n, n ) = 1
   //    Comb( n, r ) = 0 if r > n  or r < 0
   if ((r == 0) || (r == n))  return 1;
   else
      if ((r > n) || (r < 0))  return 0;
      else
         return  factdivdiv( n, r, n-r );
   }
//-----------------------END OF Combination OCUNT


function formatValue(decimalValue, decimalNum)
{
	var retVal;
	retVal = Math.round(decimalValue * Math.pow(10,decimalNum)) / Math.pow(10,decimalNum);
	retVal = formatCurrency(retVal);
	return retVal
}

function formatCurrency(num)
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+'.'+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + num + ',' + cents);
}

function oturumaAta() {
    var sisisss = sistemiHazirla();
    var sonuccc = kuponuOnayaHazirla();
    var http = GetXmlHttpObject();
    var data = "sonuc=" + encodeURIComponent(sonuccc)+"&sistem="+sisisss+"&misli="+document.myForm.multiplier.value;
    
    http.open("POST", 'oturum-ata?'+data, true);

    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    http.setRequestHeader("Content-length", data.length);

    http.setRequestHeader("Connection", "close");


    http.send(data);
}


function GetXmlHttpObject()
{
    var ajaxRequest = null;  // Ajax degiskeni..
    try {
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e) {
        // Internet Explorer Browsers
        try {
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                // Bi terslik var..
                alert(e);
            }
        }
    }
    return ajaxRequest;
}


function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

function maclistesisorter(a,b){
 return a.matchid-b.matchid;
}

function numericsorter(a,b){
 return a-b;
}



function kuponuOnayaHazirla(){

    //matchid-banko-odd-gametype-teams-mbs-guess seklinde gonderiyoruz.

var sonuc="";
   var maclistesi=getMaclistesi();

maclistesi=maclistesi.sort(maclistesisorter);
   for (i=0,len=maclistesi.length;i<len;i++){
       var match=maclistesi[i];
        sonuc+=getMatchIdFromMATCHID(match.matchid)+"*";
       sonuc+=(!match.banko?0:match.banko)+"*";
       sonuc+=match.odd+"*";
       sonuc+=match.gameType+"*";
       sonuc+=match.homeTeam+"*";
       sonuc+=match.mbs+"*";
       sonuc+=match.guess+"*";
       if (match.eventCode && isEventTypeSpecialOrAntepost(match.eventType)){
           sonuc+=match.eventCode+"*";
        }
       sonuc+="~";

   }
return sonuc;
}

String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}

function GetXmlHttpObject()
{
    var ajaxRequest = null;  // Ajax degiskeni..
    try {
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e) {
        // Internet Explorer Browsers
        try {
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                // Bi terslik var..
                alert(e);
            }
        }
    }
    return ajaxRequest;
}

function cnvToYTL(myTL)
{
    var lValue = (myTL);
    lValue = lValue.replace(".", "");
    lValue = lValue.replace(".", "");
    lValue = lValue.replace(".", "");
    lValue = lValue.replace(".", "");
    lValue = lValue.replace(".", "");
    lValue = lValue.replace(".", "");
    lValue = lValue.replace(".", "");
    lValue = lValue.replace(".", "");
    lValue = lValue / 1000000;
    lValue = toDollarsAndCents(lValue);
    lValue = lValue.replace(".", ",");

    return lValue;
}


function iddaaCouponOnayla() {

    if (errorCheck()) {
                document.myForm.sistem.value = sistemiHazirla();
                document.myForm.sonuc.value = kuponuOnayaHazirla();
                document.myForm.submit();
    }

}

   function replaceAll( str, from, to ) {
            var idx = str.indexOf( from );


            while ( idx > -1 ) {
                str = str.replace( from, to );
                idx = str.indexOf( from );
            }

            return str;
        }


//Sistemi hazirlar
function sistemiHazirla() {
    donenSistem = "";
    var myform;
try{
  myform=parent.document.myForm;
}catch(e){
    myform=document.myForm;
}

var allelems=document.myForm.elements;
 if (allelems){
       for (var p = 0,len=allelems.length; p < len; p++)
            {
               if (allelems[p].getAttribute("id") && allelems[p].getAttribute("id").startsWith("combinations")){
                    if (allelems[p].checked) {
                        donenSistem = donenSistem + "," + allelems[p].value;
                    }
               }
        }
    }

    return donenSistem;
}

function errorCheck() {
    var maclistesi=getMaclistesi();
    var systems=getSystems();
    var combinations=Combinations;
    var  bankoSayisi = bankoMaclariVer(maclistesi).length;
    var sistemSayisi = combinations.length;
    var doublematches=getDoubleMatches(maclistesi);

  if (maclistesi.length==0){
            alert("Önce maç seçmeniz gerekiyor!");
            return false;
    }

    if (getUniqueMatchCount(maclistesi)>30){
          alert("Bir kuponda en fazla 30 maç seçebilirsiniz!");
          return false;
    }
  if (bankoSayisi>0 && (systems.length ==0 )){
        alert ("Sistem Seçmeden banko oynayamazsınız.");
       return false;
   }
    var kuponadetvalue=1;
     var kuponAdet= document.getElementById("KuponAdet");
   if (kuponAdet){
       kuponadetvalue=kuponAdet.value;
   }
    var misli= document.myForm.multiplier.value;

   var couponTutar=document.getElementById("kolonCount").value*misli;
    if (couponTutar<2){
        alert (" 1 Ocak 2010 itibariyle, minimum kupon tutarı Spor Toto tarafından 2 TL'ye yükseltilmiştir.\nLütfen kuponunuzu minimum 2 TL olacak şekilde yeniden düzenleyiniz.");
        return false;
    }

    var tutar=document.getElementById("kolonCount").value*misli/kuponadetvalue;
   if (tutar>=1000){    //Tutar 2500 liradan daha fazla olamz
         alert("Kupon bedeli 1.000 TL ve üzeri olamaz.");
          return false;
    }

    var sistem0var=false;
    var sistem1var=false;
    for (i=0;i<systems.length;i++){
        if (systems[i]==0)
            sistem0var=true;
        if (systems[i]==1)
            sistem1var=true;
    }

    if (sistem0var && systems.length==1){//sadece sistem 0 var
        alert("Sistem 0 oynarken farklı bir sistem daha seçmelisiniz.");
          return false;
    }


var isValid=true;
for (ijx=0,len=combinations.length;ijx<len;ijx++){
         isValid&=combinations[ijx].valid;
    }

    if (!isValid){
       alert ("Kuponunuz minimum bahis sayısını (MBS) karşılamamaktadır. Kuponunuzu kontrol ediniz.");
        return false;
    }

    /**
     * ??mdi de ilkyar?/mac sonucu oynaerken sistem 1 ve di?erlerinden birkac tane se?mi??se validation'?n?n yapiyoz.
     */
    var threeColonluIYMSTercih=isThereIYMSInDoubleMatches(doublematches);

  if (threeColonluIYMSTercih){
          if (systems.length==0){
              alert ("İY/MS oyununda aynı maça birden fazla tercihte bulunmuşsanız sistem 1 veya sistem 0 oynamalısınız.");
              return false;
          }
      else {  //Sistem se?mi? ise secti?i sitemlere bakcaz.
               if (systems.length>0 && !sistem1var){
                   alert ("İY/MS oyununda aynı maça birden fazla tercihte bulunmuşsanız sistem 1 veya sistem 0 oynamalısınız.");
                    return false;
               }
           if (systems.length>2 && !sistem1var ){
                   alert ("İY/MS oyununda aynı maça birden fazla tercihte bulunmuşsanız sistem 1 veya sistem 0 dan başka sistem  oynayamazsınız.");
                    return false;
               }
          }
  }

    return true;
}


function makeBanko(mackodu,gametype,eventCode){
var input=document.getElementById("banko"+mackodu);
var   secilenMaclar=getMaclistesi();
if (eventCode!='undefined')
    mackodu+="."+eventCode;

for (i=0,len=secilenMaclar.length; i<len;i++){
    if (secilenMaclar[i].matchid==mackodu ){
                 if (input.checked){
                       secilenMaclar[i].banko = 1;
                      }
                else{
                    secilenMaclar[i].banko = 0;
                }
            }
    }
setMaclistesi(secilenMaclar);
hesapla();

}


function pause(milliseconds) {
	var dt = new Date();
	while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}


function addRowToTableHazir(eventType,genismi,mackodu, macadi,oran,oyuntipi,MBS,tercih,banko,eventDesc,eventCode)
{
	pause(76);
	addRowToTable(eventType,genismi,null,mackodu, macadi,oran,oyuntipi,MBS,tercih,banko,eventCode,eventDesc);
}
 function tabloyaekleAQ(eventType,genismi,el,mackodu, macadi,oran,oyuntipi,MBS,tercih,banko,bankodisabled,Eventcode,eventDesc) {
      var myColor='#aadf68';
            var tbl = document.getElementById('couponTable');
          var lastRow = tbl.rows.length;


          // if there's no header row in the table, then iteration = lastRow + 1
          var tblindex=0;
          for (i=0;i<lastRow;i++) {
              var idxx=tbl.rows[i].id;
              if (idxx && idxx!='' && idxx.indexOf('tr')>-1 ) {
                   idxx=idxx.substring(2,idxx.length)  ;
                  idxx=parseInt(idxx);
                  if (mackodu>idxx){
                     tblindex=tbl.rows[i].rowIndex+1;
                    }
              }
          }

     var convertedMatchCode=getConvertedMatchCode(mackodu,Eventcode);

  var cizgiSonaEklencek=false;

      if (tblindex>0){
        var row=tbl.insertRow(tblindex);
         row.setAttribute("id",mackodu+"*");

             var ax = row.insertCell(0);
            ax.colSpan = 3;
            ax.innerHTML = "";

                if ( document.all ){//Explorer
                ax.className="tdlizgili";
          }else {
              ax.setAttribute("class","tdlizgili");
          }
      }
     else {
          tblindex=-1;
          cizgiSonaEklencek=true;
      }
            var row = tbl.insertRow(tblindex+1);
            row.setAttribute('id',"tr"+mackodu);
            if (Eventcode && Eventcode>0){
                row.setAttribute('id',"tr"+Eventcode+"_"+mackodu);
            }else {
                row.setAttribute('id',"tr"+mackodu);
            }

            var cell = row.insertCell(0);
            cell.setAttribute("width","32");
            cell.setAttribute("align","center");
            cell.style.padding="8px 0px 8px 0px";
            cell.innerHTML="<input type='checkbox'  onClick=\"makeBanko("+mackodu+",'"+oyuntipi+"','"+Eventcode+"');\" title='Banko olarak seç' name='banko' id=banko" + mackodu +(banko==1?" checked='checked'":"") +(bankodisabled?" disabled=disabled ":"")+"><BR>";

            if (eventType==VOLLEYBALL_EVENTS){
                   cell.innerHTML+="<img src='/iddaa/images/icons/icon_volleyball.gif' alt='Voleybol' width='16' height='16' title='Voleybol' style='margin-top:6px' /><br />";
            }else if (isEventTypeBasketball(eventType)){
                   cell.innerHTML+="<img src='/iddaa/images/icons/icon_basketball.gif' alt='Basketbol' width='16' height='16' title='Basketbol' style='margin-top:6px' /><br />";
            }else if (eventType==F1_EVENTS|| eventType==MOTOGP_EVENTS|| eventType==SUPER_SPORT_EVENTS|| eventType==WRC_EVENTS ){
                   cell.innerHTML+="<img src='/iddaa/images/icons/icon_motorsports.gif' alt='Motor Sporları' width='16' height='16' title='Motor Sporları' style='margin-top:6px' /><br />";
            }else if (eventType==TENIS_EVENTS){
                   cell.innerHTML+="<img src='/iddaa/images/icons/icon_tennis.gif' alt='Tenis' width='16' height='16' title='Tenis' style='margin-top:6px' /><br />";
            }else if (eventType==BILLIARD_EVENTS){
                   cell.innerHTML+="<img src='/iddaa/images/icons/icon_billiard.gif' alt='Bilardo' width='16' height='16' title='Bilardo' style='margin-top:6px' /><br />";
            }else if (eventType==ATLETISM_EVENTS){
                   cell.innerHTML+="<img src='/iddaa/images/icons/icon_atletizm.gif' alt='Atletizm' width='16' height='16' title='Atletizm' style='margin-top:6px' /><br />";
            }else if (eventType==HENTBOL_EVENTS){
                   cell.innerHTML+="<img src='/iddaa/images/icons/icon_handball.gif' alt='Hentbol' width='16' height='16' title='Hentbol' style='margin-top:6px' /><br />";
            }else{
                cell.innerHTML+="<img src='/iddaa/images/icons/icon_football.gif' alt='Futbol' width='16' height='16' title='Futbol' style='margin-top:6px' /><br />";
            }


            cell = row.insertCell(1);
            cell.setAttribute("width","176");
            cell.setAttribute("align","left");
            cell.style.padding="5px 0px 6px 0px";


             var newMacAdi = macadi;
            if (Eventcode && Eventcode>0){
                newMacAdi=eventDesc+" ("+macadi+")";
                cell.innerHTML="<strong>"+Eventcode +"</strong>";
            }
            else
            {
                cell.innerHTML="<strong>"+mackodu +"</strong>";
            }
            cell.innerHTML+="&#160;&#160;"+newMacAdi+"<br />";
            cell.innerHTML+="Mbs: <span class='fntBold'>"+MBS+"</span>&#160;&#160;";


            //Oyun Tipi Imagı
              var myHint =  "";
              var imagelink="";
              if(oyuntipi=="F")  {imagelink = "/iddaa/images/icons/iddaa_ms.gif"; myHint = "Oyun Tipi : Maç Sonucu"; }
              else if(oyuntipi=="DC") {imagelink = "/iddaa/images/icons/iddaa_cs.gif";  myHint = "Oyun Tipi : Çifte Şans"; }
              else if(oyuntipi=="SF") {imagelink = "/iddaa/images/icons/iddaa_im.gif"; myHint = "Oyun Tipi : İlk Yarı/Maç Sonucu"; }
              else if(oyuntipi=="SC") {imagelink = "/iddaa/images/icons/iddaa_sk.gif"; myHint = "Oyun Tipi : Maç Skoru"; }
              else if(oyuntipi=="H") {imagelink = "/iddaa/images/icons/iddaa_ha.gif"; myHint = "Oyun Tipi : Handikaplı Maç Sonucu"; }
              else if(oyuntipi=="UO"&& eventType!=BASKETBALL_EVENTS) {imagelink = "/iddaa/images/icons/iddaa_au.gif"; myHint = "Oyun Tipi : Altı Üstü"; }
              else if(oyuntipi=="UO"&& eventType==BASKETBALL_EVENTS) {imagelink = "/iddaa/images/icons/iddaa_ts.gif"; myHint = "Oyun Tipi : Toplam Sayı"; }
              else if(oyuntipi=="GS" ) {imagelink = "/iddaa/images/icons/iddaa_tg.gif"; myHint = "Oyun Tipi : Toplam Gol"; }
              else if(oyuntipi=="S") {imagelink = "/iddaa/images/icons/iddaa_iy.gif"; myHint = "Oyun Tipi : İlk Yarı Sonucu"; }

             else  if (isEventTypeSpecial(eventType))
                              {imagelink = "/iddaa/images/icons/iddaa_oe.gif"; myHint = "Oyun Tipi : Özel Etkinlik"; }
            else if (isEventTypeAntepost(eventType)){
                          imagelink = "/iddaa/images/icons/iddaa_uv.gif"; myHint = "Oyun Tipi : Uzun Vadeli";
                        }

            var  oyuntipiImage = "<IMG SRC='" + imagelink + "' ALT='" + myHint + "' WIDTH='21' HEIGHT='13' title='"+myHint+"' style='margin-bottom:-3px'  >";
            //----------------------------------ORANI YAPIYOZ SIMDI.
            var tercihx=tercih;
            var tercihremove=tercih;
            if (oyuntipi=="UO"){
                  if (tercih=='1')
                        {tercihx = "Altı";}
                  else if (tercih=='2')
                        {tercihx="Üstü"}
              }
            if (oyuntipi=='GS' && tercih=='7P')
            {
                tercihx='7+';
            }
            if (oyuntipi=='SC')
            {
             tercihx=tercih.replace("5","5+ ")
            }
            if (Eventcode && Eventcode>0){
                tercihx=tercih.substr(tercih.indexOf('::')+2,tercih.length);
                tercihremove=tercih.substr(0,tercih.indexOf('::'));
            }
            
            cell.innerHTML+=oyuntipiImage;
            cell.innerHTML+="&#160;&#160;<strong id='tercih"+mackodu+"'>"+trim(tercihx);
            cell.innerHTML+= "</strong> : <strong id='oran"+mackodu+"'>"+oran+"</strong>";

            
             cell = row.insertCell(2);
            cell.setAttribute("width","22");
            cell.setAttribute("align","center");
            cell.setAttribute("valign","top");
            cell.style.padding="8px 0px 6px 0px";
            cell.innerHTML+="";

            var deleteimage=document.createElement("img");
            deleteimage.setAttribute("src","/iddaa/images/iddaa/delete_12.gif");
            deleteimage.setAttribute("width","12");
            deleteimage.setAttribute("id","deleteimage"+mackodu);
            deleteimage.setAttribute("alt","Bu seçimi sil");
			deleteimage.setAttribute("style","cursor:pointer");
            deleteimage.setAttribute("height","12");
            deleteimage.setAttribute("title","Bu seçimi sil");

                var fnc ;
                if (Eventcode && isEventTypeSpecialOrAntepost(eventType)){
                      fnc= function (mk,ot,trch,ev){
                                return function(){ rrftOzelEtkinlik(true,mk, ot,trch,ev); }
                            }(convertedMatchCode,oyuntipi,tercihremove,Eventcode);
                        }
                else{
                      fnc= function (eventType,mk,ot,trch,genis){
                                return function(){ rrft(eventType,true,mk, ot,trch,genis); }
                            }(eventType,convertedMatchCode,oyuntipi,tercihremove,genismi);
                }
                    deleteimage.onclick=fnc;
                    cell.appendChild(deleteimage);


     if (cizgiSonaEklencek&& lastRow>0){
          var row=tbl.insertRow(tblindex+2);
         row.setAttribute("id",mackodu+"*");

             var ax = row.insertCell(0);
            ax.colSpan = 3;
            ax.innerHTML = "";

              if ( document.all ){//Explorer
                    ax.className="tdlizgili";
              }else {
                  ax.setAttribute("class","tdlizgili");
              }

     }


           if (el){
                el.parentNode.setAttribute("bgColor",myColor);
            }
     if (genismi=='detay'){
         var framexz=null;
            framexz=document.getElementById('maclistesi');

           var idddd=""+(mackodu)+"_"+oyuntipi+"_"+tercih;

             var doc = getFrameDoc(framexz);

             if(doc==null){
            	 return;
             }

           var  tercihtd=doc.getElementById(idddd);
            if (tercihtd){
                tercihtd.setAttribute("bgColor",myColor);
            }else {//Tr nin tumunu boyuyoz.
                  if (framexz.location)
                        myframeName=framexz.location.href;
                   else if (framexz.src)
                        myframeName=framexz.src;
                  var trxx=doc.getElementById("tr_row"+(mackodu));
                    var tr_table =doc.getElementById("tr_table"+(mackodu));

                      var currentEventType=1;
                        var currentgameType="";
                        if (myframeName.indexOf("eventType")>-1){
                            currentEventType=myframeName.substring(myframeName.indexOf("eventType")+10,myframeName.indexOf("eventType")+11);
                        }
                        if (myframeName.indexOf("gameType")>-1){
                            var newsrc=myframeName.substring(myframeName.indexOf("gameType")+9,myframeName.length);
                            currentgameType=newsrc.substring(0,newsrc.indexOf("&"));
                        }

                    if (trxx){
                        var cellsx =trxx.cells;
                          var starttd=0;
                            var endtd=cellsx.length;
                            if (currentEventType==1 && currentgameType=='SF'){
                                starttd=6;
                                endtd=cellsx.length-1;
                            }else if (currentEventType==1 && currentgameType==''){
                                starttd=6;
                                endtd=cellsx.length-1;
                            }else if (currentEventType==1 && currentgameType=='GS'){
                                starttd=6;
                                endtd=cellsx.length-1;
                            }else if (currentEventType==2 && currentgameType=='SF'){
                                starttd=10;
                            }else if (currentEventType==2 && currentgameType==''){
                                starttd=6;
                            }
                        for (kl=starttd;kl<endtd;kl++){
                            cellsx[kl].setAttribute("bgColor",myColor);
                        }
                   }
                 if (tr_table ){//Table i, kaldırcaz.
                        tr_table.setAttribute("bgColor",myColor);
                    }
            }

     }

            kuponAreaAdd(eventType,mackodu,oran,oyuntipi,MBS,macadi,tercih,banko,Eventcode);
  }





function addRowToTable(eventType,genismi,el,mackodu, macadi,oran,oyuntipi,MBS,tercih,banko,EventCode ,eventDesc )
{

 var tbl= document.getElementById('couponTable');
    var myColor='#aadf68';

 var   secilenMaclar=getMaclistesi();

    document.getElementById("couponEmptyDiv").style.display ="none";
    document.getElementById("couponDiv").style.display ="block";

 var iteration = "";

 var SamematchAndGameExists=false;
 var SamematchExists=false;
 var SamematchAndGameAndGuessExists=false;
 var matchForDiffGameExists=false;
 var matchForSameEventExists=false;


    var framexx=document.getElementById('maclistesi');

    var doc = null;
     if(framexx&&framexx.contentDocument)
        // Firefox, Opera
        doc = framexx.contentDocument;
     else if(framexx&&framexx.contentWindow)
        // Internet Explorer
        doc = framexx.contentWindow.document;
     else if(framexx&&framexx.document)
        // Others?
        doc = framexx.document;

var convertedMatchCode=getConvertedMatchCode(mackodu,EventCode);

var uvdegil=(!isEventTypeSpecialOrAntepost(eventType));
    //ne var ne yok bak?yoz....
    for (i=0,axc=secilenMaclar.length; i<axc;i++){
        if (uvdegil&&secilenMaclar[i].matchid==convertedMatchCode && secilenMaclar[i].gameType!=oyuntipi ){
                matchForDiffGameExists=true;
                }
         if (uvdegil&&secilenMaclar[i].matchid==convertedMatchCode && secilenMaclar[i].gameType==oyuntipi  && secilenMaclar[i].guess==tercih){
                SamematchAndGameAndGuessExists =true;
                }
         if (uvdegil&&secilenMaclar[i].matchid==convertedMatchCode && secilenMaclar[i].gameType==oyuntipi ){
             SamematchAndGameExists=true;
         }
        if (uvdegil&&secilenMaclar[i].matchid==convertedMatchCode ){
          SamematchExists=true;
        }
        if (!uvdegil&&(secilenMaclar[i].gameType==oyuntipi  )&& secilenMaclar[i].eventCode==EventCode&& secilenMaclar[i].matchid==convertedMatchCode){
            matchForSameEventExists=true;
            SamematchExists=true;
            var guess=secilenMaclar[i].guess;
            guess=guess.substr(0,guess.indexOf('::'));
            var tercihx=tercih.substr(0,tercih.indexOf('::'))
            if (guess==tercihx){
               SamematchAndGameAndGuessExists =true;
            }
        }
    }

if(!SamematchExists) {
                       var uniqueMatchCount = getUniqueMatchCount(secilenMaclar);
                       if (uniqueMatchCount >= 30){
                           alert ("Bir Kuponda en fazla 30 maç seçebilirsiniz.");
                           return false;
                       }
            tabloyaekleAQ(eventType,genismi,el,mackodu, macadi,oran,oyuntipi,MBS,tercih,banko,false,EventCode,eventDesc  );

  } else if (SamematchExists){//    Digerleri i?in ilkini kald?r?yoz.
        if (oyuntipi=='F' && !SamematchAndGameAndGuessExists && !matchForDiffGameExists && eventType==BASKETBALL_EVENTS){//Basket iÃ§in ikinciyi ekleyemez.
                alert ("Basketbol  oyunu için ikinci tercihte bulunamazsınız.");
                return;
        }  if (oyuntipi=='F' && !SamematchAndGameAndGuessExists && !matchForDiffGameExists && eventType==VOLLEYBALL_EVENTS){//Basket iÃ§in ikinciyi ekleyemez.
                alert ("Voleybol  oyunu için ikinci tercihte bulunamazsınız.");
                return;
        }
        if ((oyuntipi=='F') && !SamematchAndGameAndGuessExists && !matchForDiffGameExists  && eventType==FOOTBALL_EVENTS) {//ikinciyi ekliyoz.sadece  mac sonucu oyunu i?in
                    var trx=window.document.getElementById("tr"+mackodu);
                     if (trx){
                            var result=getMatchByMatchId(secilenMaclar,mackodu,oyuntipi);
                              var tercihElement=document.getElementById("tercih"+mackodu);
                               var oranElement=document.getElementById("oran"+mackodu);
                               tercihElement.innerHTML=""+result[0].guess+"/"+tercih;
                               oranElement.innerHTML=""+result[0].odd+"/"+oran;
                               var  framexz;
                         if (document.getElementById("maclistesi"))
                            {
                                framexz=document.getElementById('maclistesi');
                            }else {
                                framexz=parent.document.getElementById('maclistesi');
                         }
                                currentFrameDocument= getFrameDoc(framexz);
                            if (result.length==2)    //mac listesinden kald?r?yoz.
                            {
                                var silincekMatch=result[1];
                                 var idddd=""+(silincekMatch.matchid)+"_"+silincekMatch.gameType+"_"+silincekMatch.guess;
                                var  tercihtd=currentFrameDocument.getElementById(idddd);

                                if (tercihtd){
                                    tercihtd.setAttribute("bgColor",'#e8e8e8');
                                }
                                if (genismi=='detay'){
                                    var elementFrame=el;
                                    while (elementFrame.parentNode){
                                        elementFrame=elementFrame.parentNode;
                                    }

                                    tercihtd=elementFrame.getElementById(idddd);
                                    if (tercihtd){
                                        tercihtd.setAttribute("bgColor",'#f2f7e6');
                                    }
                                }

                                removeMatchByIdAndGuess(convertedMatchCode,result[1].guess,result[1].gameType);
                            }

                          if (el){
                                el.parentNode.setAttribute("bgColor",myColor);
                          }
                         if (genismi=='detay'){
                               var idddd=""+(mackodu)+"_"+oyuntipi+"_"+tercih
                               var  tercihtd=currentFrameDocument.getElementById(idddd);
                               if (tercihtd){
                                       tercihtd.setAttribute("bgColor",myColor);
                               }
                         }


                         if (document.getElementById("tr"+mackodu)){
                                   trx=document.getElementById("tr"+mackodu);
                               }
                               else{
                                  trx=parent.document.getElementById("tr"+mackodu)
                              }

                         var imgcell=trx.cells[2].getElementsByTagName("img")[0];
                          var fnc= function (eventType,mk,ot,genis){
                                        return function(){ rrftMultiple(eventType,true,mk, ot,genis); }
                                    }(eventType,convertedMatchCode,oyuntipi,genismi);

                         imgcell.onclick=fnc;
                            kuponAreaAdd(eventType,mackodu,oran,oyuntipi,MBS,macadi,tercih,banko);
                         }
                }
      else if (!uvdegil &&  !matchForSameEventExists) {//Antepost Oyunu i?in farkl? Evetnlar i?i?n oyun oynayabilir.
                    tabloyaekleAQ(eventType,genismi,el,mackodu, macadi,oran,oyuntipi,MBS,tercih,banko,true,EventCode,eventDesc  );
                }
        else if (oyuntipi=='SF'&& !SamematchAndGameAndGuessExists && !matchForDiffGameExists) {//ikinciyi ucunucyu  ekliyoz.ilk yar? mac sonucu oyunu i?in
                     for (i=0;i<secilenMaclar.length;i++){
                            if (secilenMaclar[i].matchid==mackodu){
                                   secilenMaclar[i].banko=0;
                            }
                        }
                    tabloyaekleAQ(eventType,genismi,el,mackodu, macadi,oran,oyuntipi,MBS,tercih,banko,true ,EventCode,eventDesc   );
                    //Burda sistem 1 secenegini aktif hale getircez.Digerlerini kald?rcaz.
                    //Bankodisabled ise daha eski maclari da disable ediyoz.
                    iYMSleriDisableEt(getMaclistesi(),genismi,convertedMatchCode);

                }
    else if (oyuntipi=='SF'&& SamematchAndGameAndGuessExists && !matchForDiffGameExists) {//DAha onceden sectigini kald?r?yoz.   SF oyunu için
                       //Burda mac? kald?r?yoz.
                   if (genismi=='detay'){
                             if (el){
                                el.setAttribute("bgColor",'daecc2');
                            }
                      }else if (genismi=='genis'){//geni?  ise buray? yapiyoz.
                          //cellin imdexine gore renklendirme yapiyoz.
                          var index=el.parentNode.cellIndex;
                          var trx=el.parentNode.parentNode;
                            trx.cells[index].setAttribute("bgColor","");
                      }
                    removeMatchByIdAndGuess(mackodu,tercih,oyuntipi);
                    secilenMaclar=getMaclistesi();
                    rrft(eventType,true,mackodu,oyuntipi,tercih,genismi,el);
                   iYMSleriEnableEt(getMaclistesi(),convertedMatchCode,genismi);

                }
    else if (uvdegil && SamematchAndGameAndGuessExists && !matchForDiffGameExists ) {//burda  secilen oyunun tecihini  kaldırıyoruz. (Ustune tıklayaka kaldırmak ıstediğinde)
                        //Burda mac? kald?r?yoz.
                    removeMatchByIdAndGuess(convertedMatchCode,tercih,oyuntipi);
                    secilenMaclar=getMaclistesi();
                      var trxx;
                   if (document.getElementById("tr"+mackodu)){
                        trxx=document.getElementById("tr"+mackodu);
                    }
                    else{
                       trxx=parent.document.getElementById("tr"+mackodu)
                   }

                         var idddd=""+(mackodu)+"_"+oyuntipi+"_"+tercih;
            
                        var currentFrameDocument=null;
                        if (genismi=='genis'){
                         if (el.ownerDocument)
                                    currentFrameDocument=el.ownerDocument;
                             else {
                                 currentFrameDocument=el.parentNode;
                                   while (currentFrameDocument.parentNode){
                                       currentFrameDocument=currentFrameDocument.parentNode;
                                   }
                             }
                        }else if (genismi=='detay'){
                           var  framexz=parent.document.getElementById('maclistesi');
                           currentFrameDocument= getFrameDoc(framexz);
                        }
                         var  tercihtd=currentFrameDocument.getElementById(idddd);
                        if (tercihtd){
                            var oldTdColor="#f2f7e6";
                            if ((oyuntipi=='F'|| oyuntipi=='S') && eventType==FOOTBALL_EVENTS){
                                    oldTdColor='#e8e8e8';
                                }
                            tercihtd.setAttribute("bgColor",oldTdColor);
                          }
                        var result=getMatchByMatchId(secilenMaclar,convertedMatchCode,oyuntipi);

                         if (genismi=='detay'){
                                 var elementFrame;
                             if (el.ownerDocument)
                                    elementFrame=el.ownerDocument;
                             else {
                                 elementFrame=el.parentNode;
                                   while (elementFrame.parentNode){
                                       elementFrame=elementFrame.parentNode;
                                   }
                             }

                               var idddd=""+mackodu+"_"+oyuntipi+"_"+tercih
                                var tercihtdlv=elementFrame.getElementById(idddd);
                               if (tercihtdlv){
                                       tercihtdlv.setAttribute("bgColor",'#f2f7e6');
                               }
                                if (!tercihtd) {     //Kaldırıyoz.TR yi de
                                         var trx=doc.getElementById("tr_row"+mackodu);
                                        var tr_table =doc.getElementById("tr_table"+mackodu);

                                        if (framexx.location)
                                            myframeName=framexx.location.href;
                                       else if (framexx.src)
                                            myframeName=framexx.src;
                                        var currentEventType=1;
                                        var currentgameType="";
                                        if (myframeName.indexOf("eventType")>-1){
                                            currentEventType=myframeName.substring(myframeName.indexOf("eventType")+10,myframeName.indexOf("eventType")+11);
                                        }
                                        if (myframeName.indexOf("gameType")>-1){
                                            var newsrc=myframeName.substring(myframeName.indexOf("gameType")+9,myframeName.length);
                                            currentgameType=newsrc.substring(0,newsrc.indexOf("&"));
                                        }

                                        if (trx&& result.length==0)
                                            {
                                                var cells =trx.cells;
                                                  var starttd=0;
                                                    var endtd=cells.length;
                                                    if (currentEventType==1 && currentgameType=='SF'){
                                                        starttd=6;
                                                        endtd=cells.length-1;
                                                    }else if (currentEventType==1 && currentgameType==''){
                                                        starttd=6;
                                                        endtd=cells.length-1;
                                                    }else if (currentEventType==1 && currentgameType=='GS'){
                                                        starttd=6;
                                                        endtd=cells.length-1;
                                                    }else if (currentEventType==2 && currentgameType=='SF'){
                                                        starttd=10;
                                                    }else if (currentEventType==2 && currentgameType==''){
                                                        starttd=6;
                                                    }
                                                for (kl=starttd;kl<endtd;kl++){
                                                    var tempColor="#f2f7e6";
                                                    if (currentEventType==1 && currentgameType=='' && (kl==6||kl==8||kl==10 || kl==16||kl==18|| kl==20)){
                                                        tempColor="#e8e8e8";
                                                    }
                                                     //Burda Olabilecek Rengi Seccez.
                                                    cells[kl].setAttribute("bgColor",tempColor);
                                                }
                                            }
                                    else if (tr_table && result.length==0){//Table i, kaldırcaz.
                                            tr_table.setAttribute("bgColor","#F7F7F7");
                                        }
                               }
                         }
                       if (trxx){
                           if (result.length>0){
                                var tercihElement=document.getElementById("tercih"+mackodu);
                                var oranElement=document.getElementById("oran"+mackodu);
                                tercihElement.innerHTML=""+result[0].guess;
                                oranElement.innerHTML=""+result[0].odd;
                           }
                           else {//Burda TR yi kaldırııyoz.
                               removeMatchFromTable(tbl,trxx);
                           }
                        }
                   hesapla();
                }
         else if (!uvdegil && SamematchAndGameAndGuessExists && matchForSameEventExists){//ikinci tıklamalı Ozel ETkinlik oyununu kaldýrýyoz.
                   //     removeMatchByIdAndGuessOZELETKINLIK(convertedMatchCode,tercih,oyuntipi,EventCode);
                     //   secilenMaclar=getMaclistesi();
                       tercih=tercih.substr(0,tercih.indexOf("::"));
                        rrftOzelEtkinlik(true,convertedMatchCode,oyuntipi,tercih,EventCode,el);
                        }
         else if (oyuntipi!='F' &&((uvdegil && SamematchAndGameAndGuessExists && !matchForDiffGameExists)||(!uvdegil &&matchForSameEventExists) )) {//burda ikinci secilen mac sonucu tercihini kald??ryoruz.
                  alert ("Bu maç için bir tercihiniz bulunmakta.Bu tercihe oynamak için lütfen eski tercihinizi kaldırınız.  ");
                }
           else if (matchForDiffGameExists){//burda da ilk secileni kald?rcaz ikinci secileni ekliycez.
                alert ("Bu maç, kuponunuzda zaten ekli durumda.\nBu oyun türünde oynamak için lütfen kuponunuzdan çıkarın.");
              }
       }
   else {
     return;
  }
}


function removeMatchFromTable(tbl,oTr) {
    var usttr;
    if (oTr.rowIndex>1)
    usttr=tbl.rows[oTr.rowIndex-1];
    if (usttr)
    {//ustunde varmı ? yoksa altında varmı bakcaz.  Cizgiyi kaldırıyoz.
        tbl.deleteRow(usttr.rowIndex);
    }
    else {
       var  alttr=tbl.rows[oTr.rowIndex+1]; //Alttaki rowu silcez.
        if (alttr)
            tbl.deleteRow(alttr.rowIndex);
    }
    tbl.deleteRow(oTr.rowIndex);
}

//Gets the given selected Match by matchid
function   getMatchByMatchId (maclistesi,mackodu,oyuntipi){
    var result=new Array();
    if (maclistesi &&maclistesi.length>0){
        for (i=0,len=maclistesi.length;i<len;i++)
                {
                    if (mackodu==maclistesi[i].matchid)
                        result.push(maclistesi[i]);
                }
    }
  return result;
}


function combine(a, q){
    if (q==a.length){
        return Array(a);
    }
    if (q==0){
        return Array();
    }
    var n = a.length - 1, l = n - q + 1, x = 0, c = [], z = -1, p, j, d, i;
    if(q > n || q < 1) return c;
    for(p = [], i = q; p[--i] = i;);
    while(x <= l){
        for(c[++z] = [], j = -1; ++j < q; c[z][j] =a[p[j]]);
        if(++p[j - 1] > n)
            while(j--)
                if(!j && x++, (d = p[j]) < l + j){
                    while(j < q) p[j++] = ++d;
                    break;
                }
    }
    return c;
}


function iYMSleriDisableEt(maclistesi,genismi,matchid){
     var tbl ;

  tbl  = document.getElementById('couponTable');

 var match=getMatchByMatchId(maclistesi, matchid);

   var checkboxtobedisabled=tbl.getElementsByTagName("input");
   for (ik=0;ik<checkboxtobedisabled.length;ik++){
       if (checkboxtobedisabled[ik].getAttribute("id")=='banko'+matchid){
           checkboxtobedisabled[ik].disabled=true;
           checkboxtobedisabled[ik].checked=false;
           var deletetr=checkboxtobedisabled[ik].parentNode.parentNode;
            var check_trIndex=checkboxtobedisabled[ik].parentNode.parentNode.rowIndex;
           var tercihkismi=document.getElementById("tercih"+matchid);
           var tercih=tercihkismi.innerHTML;

            var deleteimg=deletetr.getElementsByTagName("img")[0];
            var fnc = function (eventType,genisekran,mid,tercihx){
                            return function(){ rrft(eventType,true,mid,'SF',trim(tercihx),genisekran); }
                        }(match.matchid,genismi,matchid,tercih);
           deleteimg.onclick=fnc;
       }
       }
   }


function iYMSleriEnableEt(maclistesi,matchid,genismi){ //Et bakal?m edebilirsen.Eger
   var tbl ;

  tbl  = document.getElementById('couponTable');
    var match=getMatchByMatchId(maclistesi, matchid);

   var checkboxtobedisabled=tbl.getElementsByTagName("input");
   var matchcount=0;
   for (ik=0;ik<checkboxtobedisabled.length;ik++){
       if (checkboxtobedisabled[ik].getAttribute("id")=='banko'+matchid){
              matchcount++;
       }
   }

    if (matchcount==1){
        for (ik=0;ik<checkboxtobedisabled.length;ik++){
               if (checkboxtobedisabled[ik].getAttribute("id")=='banko'+matchid){
                   checkboxtobedisabled[ik].disabled=false;

                   var deletetr=checkboxtobedisabled[ik].parentNode.parentNode;
                    var check_trIndex=checkboxtobedisabled[ik].parentNode.parentNode.rowIndex;
                    var altrow=tbl.getElementsByTagName("tr")[check_trIndex+1];
                    var tercihkismi=document.getElementById("tercih"+matchid);
                    var tercih=tercihkismi.innerHTML;
                     var fnc = function (eventType,genisekran,mid,tercihx){
                            return function(){ rrft(eventType,true,mid,'SF',trim(tercihx),genisekran); }
                        }(match.eventType,genismi,matchid,tercih);
                   checkboxtobedisabled.onclick=fnc;
               }
           }
    }
}

function getBasketMatchCount(maclistesi){ //Et bakal?m edebilirsen.Eger
    var counter=0;
for (i=0;i<maclistesi.length; i++){
    if (maclistesi[i].eventType==BASKETBALL_EVENTS && maclistesi[i].gameType!='SF' && !isEventTypeSpecialOrAntepost(maclistesi[i].eventType))
        counter++;
}
    return counter;
}
function getBasketMatchCountAll(maclistesi){ //Et bakal?m edebilirsen.Eger basketTable kaldÃ„Â±rma Kontrolu iÃƒÂ§in
    var counter=0;
for (i=0;i<maclistesi.length; i++){
    if (maclistesi[i].eventType==BASKETBALL_EVENTS )
        counter++;
}
    return counter;
}


function getMatchIdFromMATCHID(matchid){
if (matchid.indexOf(".")>-1)
        return matchid.substr(0,matchid.indexOf("."));
 else
        return matchid;
}

function getConvertedMatchCode(matchcode,eventCode){
    if (eventCode){
        matchcode+="."+eventCode;
    }
    return matchcode;
}



function getFrameDoc(framexx) {
      var IFrameDoc=null;
      try{
    	  if (framexx.contentDocument) {
    		  // For NS6
    		  IFrameDoc = framexx.contentDocument;
    	  } else if (framexx.contentWindow) {
    		  // 	For IE5.5 and IE6
    		  IFrameDoc = framexx.contentWindow.document;
    	  } else if (framexx.document) {
    		  //	 	For IE5
    		  IFrameDoc = framexx.document;
    	  } else {
    		  return null;
    	  }
      }catch (ex) {
	}

    return IFrameDoc;
}