var tempHelp="";
var contGame=false;
var numPlayers=4;
var maxPlayers=0;
var wherePics="images/";
var cooPl1="";
var cooPl2="";
var cooPl3="";
var cooPl4="";

combs = new Array()
combs[0]='Единицы'
combs[1]='Двойки'
combs[2]='Тройки'
combs[3]='Четверки'
combs[4]='Пятерки'
combs[5]='Шестерки'
combs[6]='Пара'
combs[7]='Две пары'
combs[8]='Трио'
combs[9]='Малый фул'
combs[10]='Большой фул'
combs[11]='Стрит'
combs[12]='Каре'
combs[13]='Покер'
combs[14]='Генерал'

example = new Array()
example[0]='631145=2'
example[1]='244322=6'
example[2]='532333=12'
example[3]='414452=12'
example[4]='154554=15'
example[5]='612666=24'
example[6]='211565=10'
example[7]='545363=16'
example[8]='641166=18'
example[9]='435534=24'
example[10]='533355=24'
example[11]='546321=21'
example[12]='525355=20'
example[13]='446444=20'
example[14]='222222=12'

dice1	= new Image()
dice1.src	= wherePics+"dice1.gif"
dice2	= new Image()
dice2.src	= wherePics+"dice2.gif"
dice3	= new Image()
dice3.src	= wherePics+"dice3.gif"
dice4	= new Image()
dice4.src	= wherePics+"dice4.gif"
dice5	= new Image()
dice5.src	= wherePics+"dice5.gif"
dice6	= new Image()
dice6.src	= wherePics+"dice6.gif"
dice0	= new Image()
dice0.src	= wherePics+"dice0.gif"

PIC1	= new Image()
PIC1.src= wherePics+"picstart.gif"
PIC2	= new Image()
PIC2.src= wherePics+"picstar2.gif"
PIC3	= new Image()
PIC3.src= wherePics+"dropdice.gif"
PIC4	= new Image()
PIC4.src= wherePics+"dropdic2.gif"
PIC5	= new Image()
PIC5.src= wherePics+"passmove.gif"
PIC6	= new Image()
PIC6.src= wherePics+"passmov2.gif"
PIC7	= new Image()
PIC7.src= wherePics+"endgame.gif"
PIC8	= new Image()
PIC8.src= wherePics+"endgame2.gif"
PIC9	= new Image()
PIC9.src= wherePics+"helpgame.gif"
PIC10	= new Image()
PIC10.src= wherePics+"helpgam2.gif"

dice=new Array(6);		// dices value
ardices=new Array(6);	// dices condition
numcpl=0;				// current player
closeoper=false;		// all comb close flag


function ClearDices() {
	for(i=0;i<6;i++) {
		dice[i]=0;
		ardices[i]=false;
	}
	document.DICE01.src=dice0.src;
	document.DICE02.src=dice0.src;
	document.DICE03.src=dice0.src;
	document.DICE04.src=dice0.src;
	document.DICE05.src=dice0.src;
	document.DICE06.src=dice0.src;
}
			
function Empty(s){
var str=new String(s);
var res=true;
	if (str.length != 0) 
		for( i=0;i<=str.length;i++){
			if (str.substring(i,1) !== ' ' ){
				res=false;
				break;
			}
		}
return res;
}

function Val(strHere) {		// convert string in number
var ret=0;
	if (!Empty(strHere))
		ret = parseInt(strHere);
return ret;
}

function createNewArray(len){
	this.length=len;
	for(i=1;i<=len;i++)
		this[i]=0;
return this;
}

function Before2(someform) {
	if (contGame)
		someform.blur(); }

function WriteAtempt(player,howmany) {
var index = 16 * 4 + player;
var temp = document.results.elements[index].value;
	temp = Val(temp);
	document.results.elements[index].value = 
		temp+parseInt(howmany);
	document.all["CurrDrop"].innerText=
		document.results.elements[index].value;
}
function GetAtempt(player) {
var index = 16 * 4 + player;
return parseInt(document.results.elements[index].value);
}

function StartGame(){
var doc=window.document;
var j=0;l=0;
var p='';
var ar = new Array();
var today=new Date();
var tempDate=new Date();

	document.all.getpl.style.visibility="hidden";
	if (contGame)
		return;
	for(k=0;k<numPlayers;k++) {
		if (!Empty(doc.players.elements[k].value)) {
			j += 1;
			s = doc.players.elements[k].value;		
			ar[l] = s.toUpperCase(s);
			p = p + '\n'+ar[l++];
		}
	}
	if (j==0) {
		window.alert( 'Начать игру невозможно.	Игроки не введены.' );
		return false;
		}
	else
		if (confirm('Количество играющих: ' + j + '.' +
			p + '\nНачать игру ?')) {
			contGame=true;
			document.results.elements[0].value='';
			document.results.elements[1].value='';
			document.results.elements[2].value='';
			document.results.elements[3].value='';
			for(i=4;i<document.results.length;i++)
				document.results.elements[i].value='';
			for(l=0;l<=ar.length-1;l++) {
				document.results.elements[l].value=ar[l];
				document.results.elements[17*4+l].value=0;
			}
			maxPlayers=ar.length;
			document.all["Help"].innerText='Бросьте кости или пропустите ход';
			ClearDices();
			closeoper=false;
			numcpl=1;
			WriteAtempt(numcpl-1,3);
			WriteAbout(numcpl-1);
			if (navigator.cookieEnabled) {
				i=(today.getTime())+600000;
				tempDate.setTime(i);
				setCookie("lastpl1",ar[0],tempDate);
				setCookie("lastpl2",((ar[1])?ar[1]:""),tempDate);
				setCookie("lastpl3",((ar[2])?ar[2]:""),tempDate);
				setCookie("lastpl4",((ar[3])?ar[3]:""),tempDate);
			}
		}
}

function EndGame(){
	document.all.getpl.style.visibility="hidden";
	if (!contGame)
		return;
	if (!confirm('Вы действительно хотите закончить игру ?'))
		return;
	contGame=false;
	for(k=0;k<numPlayers;k++)
		document.players.elements[k].value=''
	maxPlayers=0;
	document.all["CurrPlayer"].innerText='';
	document.all["CurrPoint"].innerText='';
	document.all["CurrDrop"].innerText='';
	document.all["CombOut"].innerText='';
	document.all["Help"].innerText='Нажмите кнопку НАЧАТЬ ИГРУ';
	for(l=0;l<=3;l++)
		document.results.elements[l].value='Игрок '+(l+1);
	for(l=0;l<=3;l++) {
		document.results.elements[17*4+l-1].value='';
		document.results.elements[16*4+l-1].value='';
	}
}

function WriteAbout(player) {
	document.all["CurrPlayer"].innerText=
		document.results.elements[player].value;
	document.all["CurrPoint"].innerText=
		document.results.elements[17*4+player].value;
	document.all["CurrDrop"].innerText=
		document.results.elements[16*4+player].value;
}

function getRandom(x,y) {
var range=y-x+1;
var i=(""+range).length;
var rnd = Math.random();
var j = Math.pow(10,i);
var num=Math.floor(rnd*j%range) + parseInt(x)
return num
}

function DropDices() {	// avail to drop when
				// all dices=0 or any selected
var j=0;
	if (!contGame)
		return;
	for(i=0;i<6;i++) {
		j += dice[i];
		if (ardices[i]) {	// selected
			j=0;
			break;
		}
	}
	if (GetAtempt(numcpl-1)==0) {
		window.alert('У Вас нет больше попыток.\n'+
				'Укажите зачетную комбинацию\n'+
				'или пропустите ход.');
		return;
	}
	if (j != 0)
		window.alert('Сначала укажите перебрасываемую кость');
		//document.help01.Help.value='Сначала укажите перебрасываемую кость';
	else {
		for(k=0;k<6;k++)
			if (dice[k]==0 || ardices[k]) {
				dice[k]=getRandom(1,6);
				ardices[k]=false;
				j = k+4;
				if (dice[k]==1)
				   document.images[j].src=dice1.src;
				if (dice[k]==2)
				   document.images[j].src=dice2.src;
				if (dice[k]==3)
				   document.images[j].src=dice3.src;
				if (dice[k]==4)
				   document.images[j].src=dice4.src;
				if (dice[k]==5)
				   document.images[j].src=dice5.src;
				if (dice[k]==6)
				   document.images[j].src=dice6.src;
			}
		document.all["Help"].innerText='Укажите зачетную комбинацию или пропустите ход'
		WriteAtempt(numcpl-1,-1);
		Variants();
	}
}

function Control(nCombi) {
var CombiSum=0;j=0;
var Dice1 = new Array(6);
	MaxDice=6;
	if (nCombi > 6) {			// sort
		for(i=0;i<MaxDice;i++)	// copy
			Dice1[i]=dice[i];
		Dice1.sort();
	}
	if (nCombi < 7) {			// school
		for(i=0;i<MaxDice;i++)
               if (dice[i] == nCombi)
				CombiSum += nCombi;
	}
	if (nCombi == 7) {			// pair
	   j=5;
	   while ((j>=1) && (CombiSum==0)) {
           if (Dice1[j] == Dice1[j-1]) {
              CombiSum = Dice1[j]*2;
              break; }
           else
              j--;
        }
     }
     if (nCombi == 8) {		// two pairs                                       // Їа®ўҐаЄ  ¤ўге б®бҐ¤­Ёе н«Ґ¬Ґ­в®ў
        j=5;
        i=0;
        while ((j>=1) && (i < 2)) {
           if (Dice1[j] == Dice1[j-1]) {
              i++;
              CombiSum = CombiSum + Dice1[j]*2;
              j=j-2; }
           else
              j--;
        }
        CombiSum = (i < 2) ? 0:CombiSum;
	}
     if (nCombi == 9) {		// trio
	   j=5;
	   while ((j>=2) && (CombiSum==0)) {
           if (Dice1[j] == Dice1[j-1] &&
               Dice1[j] == Dice1[j-2]) {
              CombiSum = Dice1[j]*3;
              break; }
           else
              j--;
        }
     }
     if (nCombi == 10) {   	// little ful
        if (Dice1[0] == Dice1[1] &&
            Dice1[2] == Dice1[3] &&
            Dice1[4] == Dice1[5])
           CombiSum = (Dice1[0]+Dice1[2]+Dice1[4])*2;
	}
	if (nCombi == 11) {      // big ful
        if (Dice1[0] == Dice1[1] && Dice1[0] == Dice1[2] &&
            Dice1[3] == Dice1[4] && Dice1[3] == Dice1[5])
           CombiSum = Dice1[0]*3 + Dice1[3]*3;
     }
     if (nCombi == 12) {		// street
        CombiSum=21;
        for( j=0;j<=5;j++)
        	if (Dice1[j] != j+1) {
             CombiSum = 0;
             break;
          }
	}
	if (nCombi == 13) {		// kare
	   j=0;
	   while ((j <= 2) && (CombiSum==0))
		if (Dice1[j] != Dice1[j+1])
          	j++;
      	else {
			if (Dice1[j] == Dice1[j+1] &&
			    Dice1[j] == Dice1[j+2] &&
                  Dice1[j] == Dice1[j+3])
                  CombiSum = Dice1[j] * 4;
              else
                  j++;

		}
	}
     if (nCombi == 14) {		// poker
        j=0;
        while ((j <= 1) && (CombiSum==0))
		if (Dice1[j] != Dice1[j+1])
            j++;
          else {
            if (Dice1[j] == Dice1[j+1] &&
                Dice1[j] == Dice1[j+2] &&
                Dice1[j] == Dice1[j+3] &&
                Dice1[j] == Dice1[j+4])
               CombiSum = Dice1[j] * 5;
            else
               j++;
		}
	}
	if (nCombi == 15) {			// general
     	CombiSum = Dice1[1] * 6;
		for( i=1;i<MaxDice;i++ )
               if (Dice1[0] != Dice1[i]) {
                  CombiSum = 0;
                  break;
			}
	}
return CombiSum
}

function Variants()	 {		// dropped
var p='';j=0;k=0;
var i;
var temp;
	for( i=15;i>=7;i--) {
		j = Control(i);
		if (j > 0) {
			p = p + combs[i-1] + ', ';
			k++;
			if (k>4) break;
		}
	}
	temp = new String(p);
	i = temp.length;
	p = temp.substring(0,i-2)
	document.all["CombOut"].innerText=p;
}

function PassMove() {
var j=0;k=0;p='';
var p='';
	if (!contGame)
		return;
	document.all["Help"].innerText='Бросьте кости или пропустите ход';
	document.all["CombOut"].innerText='';
	ClearDices();
	if (++numcpl>maxPlayers) {
		numcpl = 1;
		if (closeoper) {		// all combs were closed
			j=0;
			for(var i=0;i<maxPlayers;i++) {
				temp=Val(document.results.elements[17*4+i].value);
				if ( j<=temp )
					if ( j=temp )
						p+=document.results.elements[i].value + ' ';
					else {
						p=document.results.elements[i].value + ' ';
						j=temp;
					}
			}
			alert('Игра закончена.\nПобедитель:\n'+p);
			document.all["Help"].innerText='Введите имена игроков и нажмите кнопку НАЧАТЬ ИГРУ';
			contGame=false;
			return;
		}
	}
	WriteAtempt(numcpl-1,3);
	WriteAbout(numcpl-1);
	document.all["Help"].innerText='Бросьте кости или пропустите ход';
	tempHelp=document.all["Help"].innerText;
}

function imgover(imgname) {
	if (!contGame)
		imgname.src=dice0.src;
}
function imgout(imgname,dicehere) {
	if (!contGame)
		imgname.src=dicehere;
}
function selectdice(imgname,whatdice) {
var f=false;
	for(i=0;i<6;i++)
		if (dice[i]>0) {	
			f=true;
			break;
		}
	if (contGame && f) {
		if (GetAtempt(numcpl-1)==0) {
			window.alert('У Вас нет больше попыток.\n'+
				'Укажите зачетную комбинацию\n'+
				'или пропустите ход.');
			return;
		}
		if (ardices[whatdice]) {  // selected
			ardices[whatdice]=false;
			k=whatdice+4;
			if (dice[whatdice]==1)
			   document.images[k].src=dice1.src;
			if (dice[whatdice]==2)
			   document.images[k].src=dice2.src;
			if (dice[whatdice]==3)
			   document.images[k].src=dice3.src;
			if (dice[whatdice]==4)
			   document.images[k].src=dice4.src;
			if (dice[whatdice]==5)
			   document.images[k].src=dice5.src;
			if (dice[whatdice]==6)
			   document.images[k].src=dice6.src;
		}
		else	{		// not selected yet
			ardices[whatdice]=true;
			imgname.src=dice0.src;
		}
	}
}

function CantDoIt(someform) {
	//window.alert('You can not do it here');
	someform.blur();
}

function CommOver(imgname,src1,mess) {
	imgname.src=src1;
	window.status=mess;
}
function CommOut(imgname,src1) {
	imgname.src=src1;
	window.status='';
}

function TestComb(comb) {
var o;
	tempHelp=document.all.Help.innerText;
	o = document.all["Help"];
	o.innerText = combs[comb] + ' ' + example[comb];
	window.status=combs[comb];
}
function RestHelp() {
	document.all["Help"].innerText=tempHelp;
	window.status='';
}

function WriteComb(nComb) {
var j = parseInt(nComb);f=false;
var index = (j+1) * 4 + numcpl - 1;
var temp = document.results.elements[index].value;
var leaders = new Array();k=0;
	if (!contGame)
		return;
	for(i=0;i<6;i++)
		if (dice[i]>0) {	
			f=true;
			break;
		}
	if (!f)
		return;
	if (document.results.elements[index].value > 0) {
		alert('Эту комбинацию Вы уже закрыли.');
		return;
	}
	i=Control(j+1);
	if (i==0) {
		alert('У Вас не выпала комбинация:\n'+
			combs[j]);
		return;
	}
	document.results.elements[index].value = i;		// writing comb
	j=0;
	closeoper=true;
	for(k=4 + numcpl-1;k<=15*4+numcpl-1;k+=4) {		// total calculating
		temp=Val(document.results.elements[k].value);
		closeoper= (temp==0) ? false : closeoper;
		j += temp;
	}
	document.results.elements[17*4+numcpl-1].value=j;	// writing total
	if (closeoper) {
		document.results.elements[17*4+numcpl-1].color="#E2D15E";
		temp=Val(document.results.elements[17*4+numcpl-1].value)
		temp += 20;				// writing bonus
		document.results.elements[17*4+numcpl-1].value = temp;
		document.all["CurrPoint"].innerText=
			document.results.elements[17*4+numcpl-1].value;
	}
	// подсветить закрывших внизу
	j=0;
	for(var i=0;i<maxPlayers;i++) {
		temp=Val(document.results.elements[17*4+i].value);
		if ( j<=temp )
			if ( j=temp )
				leaders[k++]=i;
			else {
				leaders[k]=i;
				j=temp;
			}
		}
	// подсветить лидеров в шапке
	PassMove();
}

function SlideGetPl() {
	if (ie) {
		document.all.getpl.style.visibility="visible";
		idw=window.setInterval( "MoveGetPl();",10 );
	}
	else {
		document.getpl.visibility="show";
	}
}

function MoveGetPl() {
	if (ie) {
		document.all.getpl.style.pixelTop += 5;
		if (document.all.getpl.style.pixelTop >= 60) {
			document.all.getpl.style.pixelTop = 60;
			window.clearInterval(idw); 
		}
	}
	else {
		document.getlp.top += 10;
		if (document.getpl.top >= 120) {
			document.getpl.top = 120;	}
	}
}

function getPlayers() {

	if (contGame)
		return;
	SlideGetPl();
	if (navigator.cookieEnabled) {
		cooPl1=getCookie("lastpl1");
		cooPl2=getCookie("lastpl2");
		cooPl3=getCookie("lastpl3");
		cooPl4=getCookie("lastpl4");
		document.players.player1.value=cooPl1;
		document.players.player2.value=cooPl2;
		document.players.player3.value=cooPl3;
		document.players.player4.value=cooPl4;
	}
}

function ChanColor(arg) {			// заменяет функцию в left.js
var mode=ChanColor.arguments[0];
var ob=ChanColor.arguments[1];
var f=false;
	if (ChanColor.arguments.length>2)
		f=ChanColor.arguments[2];
	if (mode==1) { 
		ob.color = "white";
		if (f) return;
		if (ie) {
			document.all.help1.style.pixelLeft=300;
			document.all.help1.style.width=300;
			document.all.help1.style.visibility="visible";
			idw=window.setInterval( "MoveHelp();",10 );
		}
		else {
			document.help1.visibility="show";
		}
	}
	else {
		ob.color = "black";
		if (f) return;
		if (ie) {
			document.all.help1.style.visibility="hidden";
			document.all.help1.style.pixelTop = 0;
		}
		else {
			document.help1.visibility="hide";
		}
	}
}

function MoveHelp() {
	if (ie) {
		document.all.help1.style.pixelTop += 5;
		if (document.all.help1.style.pixelTop >= 30) {
			document.all.help1.style.pixelTop = 30;
			window.clearInterval(idw); 
		}
	}
	else {
		document.help1.top += 10;
		if (document.help1.top >= 120) {
			document.help1.top = 120;	}
	}
}
function FuncHere() {
}


function getCookie(name) {
var prefix=name+"=";
var start=document.cookie.indexOf(prefix);
	if (start==-1)
		return "";
var end=document.cookie.indexOf(";",start+prefix.length);
	if (end==-1)
		end=document.cookie.length;
var value=document.cookie.substring(start+prefix.length,end);
return unescape(value);
}

function setCookie(name,value,expires,path,domain,secure) {
var newCookie=name+"="+escape(value)+
	((expires) ? ";expires=" + expires.toGMTString():"")+
	((path)    ? ";path="    + path                 :"")+
	((domain)  ? ";domain="  + domain               :"")+
	((secure)  ? ";secure="  + secure               :"")
	document.cookie = newCookie;
}
