// JavaScript Document

//records this time in the puzzle time folder and updates average/ best puzzle time file
var goog;
var puzzleW;
var puzzleH;
var browser;
var detect = navigator.userAgent.toLowerCase();

function resizeWindow(){

if (checkIt('safari')) browser = "Safari";
else if (checkIt('omniweb')) browser = "OmniWeb";
else if (checkIt('opera')) browser = "Opera";
else if (checkIt('webtv')) browser = "WebTV";
else if (checkIt('icab')) browser = "iCab";
else if (checkIt('msie')) browser = "IE";
else if (checkIt('firefox')) browser = "FireFox";

	var screenW = 800, screenH = 600;
	var winW = 630, winH = 460;
	if (parseInt(navigator.appVersion)>3) {
 		screenW = screen.width;
		screenH = screen.height;
		if(window.innerHeight)
        	winH = window.innerHeight;
    	else{
          if(document.documentElement){
            winH = document.documentElement.offsetHeight;
          }
          else
            winH = document.body.offsetHeight;
      }
    	if(window.innerWidth)
        	winW=window.innerWidth;
    	else{
            winW = document.body.offsetWidth;
       }
	}
	else if (navigator.appName == "Netscape" 
    && parseInt(navigator.appVersion)==3
    && navigator.javaEnabled()) 
	{
	 	var jToolkit = java.awt.Toolkit.getDefaultToolkit();
 		var jScreenSize = jToolkit.getScreenSize();
	 	screenW = jScreenSize.width;
 		screenH = jScreenSize.height;
		winW = document.body.offsetWidth;
		winH = document.body.offsetHeight;
	 
 	} 
 	var papplet = document.getElementById("puzzleapplet");
  	var content = document.getElementById("content");
  	var theApplet = document.getElementById("puzzle");

 	if (screenW == 800 && screenH==600){
 		papplet.width=winW -200;
  		papplet.height = winH -400;
  		content.width=winW - 200;
  		content.height=winH - 400;
  		if (theApplet != null){
  			theApplet.width= winW - 200;
  			theApplet.height = winH - 200;
		}
 	}else
 	{
 		if(browser=="IE"){
			papplet.width = winW - 290;
 			papplet.height = winH - 230;
			content.width = winW - 290;
			content.height = winH - 230;
			if (theApplet != null){
				theApplet.width= winW - 290;
				theApplet.height = winH - 230;
			}
		}
		else if (browser=="FireFox"){
			papplet.width = winW - 280;
 			papplet.height = winH - 230;
			content.width = winW - 280;
			content.height = winH - 230;
			if (theApplet != null){
				theApplet.width= winW - 280;
				theApplet.height = winH - 290;
			}
		}
		else if (browser=="Safari"){
			papplet.width = winW - 280;
 			papplet.height = winH - 240;
			content.width = winW - 280;
			content.height = winH - 240;
			if (theApplet != null){
				theApplet.width= winW - 280;
				theApplet.height = winH - 240;
			}
		}
		else if (browser=="Opera"){
			papplet.width = winW - 280;
 			papplet.height = winH - 290;
			content.width = winW - 280;
			content.height = winH - 290;
			if (theApplet != null){
				theApplet.width= winW - 280;
				theApplet.height = winH - 290;
			}
		}
		else{
			papplet.width = winW - 290;
 			papplet.height = winH - 230;
			content.width = winW - 290;
			content.height = winH - 230;
			if (theApplet != null){
				theApplet.width= winW - 290;
				theApplet.height = winH - 230;
			}
		}
 	}
	if(papplet.height < 400){
		papplet.height = 400;
	}
	puzzleW=papplet.width -70;
	puzzleH=papplet.height;
}

function checkIt(string)
{
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}


function generateAppletCode(img,id,acut,clip,rotation){	
	var appdiv = document.getElementById('puzzleapplet');
	var str = "<APPLET id=\"puzzle\" NAME=\"jigkids\" CODE=\"com.jigkids.dailypuzzle.DailyPuzzle\" CODEBASE=\".\" ARCHIVE=\"potd.jar\" HEIGHT=" + puzzleH + " WIDTH=" + puzzleW + " ALIGN=\"bottom\" MAYSCRIPT>";
	str = str + "games. Jigsaw Puzzles, Free Online Puzzles. online games,free games,Kids Online Game,Kid Fun, Photograph, photo, images, dogs, cats, horses.";
  str = str + "<param name=\"puz\" value=\"" + img + "\" >";
  str = str + "<param name=\"cut\" value=\"" + acut + ".zip\">";
  str = str + "<param name=\"txt\" value=\"jigkids.com 2006-2010\">";
  str = str + "<param name=\"boxmessage\" value=\"Puzzle is loading...\">";
  str = str + "<param name=\"boxbgcolor\" value=\"#D6E7F5\">"; 
  str = str + "<PARAM name=\"image\" value=\"images/JigKids.jpg\">";
  str = str + "<PARAM name=\"sid\" value=\"" + id + "\">";
  str = str + "<PARAM name=\"remo\" value=\"images/fond_applet.jpg\">";         
	str = str + "<PARAM name=\"bg\" value=\"" + puzColor + "\">";
	str = str + "<param name=\"clip\" value=\"" + clip +"\">";
	if(rotation == 0){
		str = str + "<param name=\"rot\" value=\"" + false +"\">";
	}
	else{
		str = str + "<param name=\"rot\" value=\"" + true +"\">";
	}
  str = str + "</APPLET> ";
	appdiv.innerHTML = str;
	var rot = document.getElementById('rotation');
	if (rotation == 0){
		rot.checked = false;
	}
	else{
		rot.checked = true;
	}
	appletcode=str;
	getCutName(acut);
}
  
function getCutName(id){
	var url = 'cutName.php?cut=' + id;
	AjaxRequest.get(
		{ 
			'url':url,
			'onSuccess':function(req){ loadCutName(req.responseXML); },
			'timeout':5000,
  		'onTimeout':function(req){},
			'onError':function(req){}
		}
	);
}

function loadCutName(xml){
	var html_cutName = xml.getElementsByTagName('cutname').item(0).firstChild.nodeValue;
	var pagename = document.getElementById("cutName");
	pagename.innerHTML=" - " + html_cutName;	
}


function setColor(color){
  document.getElementById("puzzle").setBckgColor(color);
}

function generateNewRecordCode(){
var appdiv = document.getElementById('puzzleapplet');

if (document.getElementById('rotation').checked==true ) {rotation=5} else {rotation=0};
var str="<form name=\"newrecord\" action=\"submit_newrecord.php\" method=\"get\"  ><br><h1>Congratulations! you own the new record for this puzzle and cut!</h1><br>";
str = str + "<h3>Choose a nickname:</h3><input type=\"text\" name=\"nickname\" value=\"\"><br><br>";
str = str + "<h3>Enter your email address:</h3><input type=\"text\" name=\"email\" value=\"\">&nbsp;";
str = str + "<input type=\"submit\" value=\"Submit\"><br><br>";
str = str + "<h3>Notify me if somebody beat my record</h3><input name=\"notify\" type=\"CHECKBOX\" value=1 checked>";
str = str + "<input type=\"hidden\" name=\"puzid\" value=\"" + puzzleid +   "\" /><input type=\"hidden\" name=\"cutid\" value=\"" + img_cut + "\"/><input type=\"hidden\" name=\"rotation\" value=\"" + rotation +   "\" /></form";

appdiv.innerHTML = str;
}

// called when user clicks on one of the photos on the ad banner
// we need to set the current puzzle to this puzzle
//pos=1 means left image pos=2 means image right
function setBannerPuzzle(pos){
	//img_small = img;
	//img_big = img;
	if (pos==1){
    img_small = "bannerImgs/imgleft.jpg";
    img_big = "bannerImgs/imgleft_b.jpg";
    img_info = "bannerImgs/imgleft_info.txt";
	}
	else{
    img_small = "bannerImgs/imgright.jpg";
    img_big = "bannerImgs/imgright_b.jpg";
    img_info = "bannerImgs/imgright_info.txt";
	}
	resetTimer();
	var thistime = document.getElementById('yourtime')
	thistime.innerHTML ="00:00";

	AjaxRequest.get(
  	{ 'url':img_info,'onSuccess':function(req){ setPuzzleBanner(req.responseText); }
  	}
	);
}

function setupBannerImages(){
	var imgl = document.getElementById("leftimg");
	var imgr = document.getElementById("rightimg");
	//imgl.src = "bannerImgs/imgleft.jpg?" + new Date().getTime();
	//imgr.src = "bannerImgs/imgright.jpg?" + new Date().getTime();
}

function getGoogleAds(){
		var googdiv = document.getElementById('googleads');
		var ifr = document.getElementsByName("google_ads_frame");
		if(ifr){
			goog = googdiv.innerHTML;
		}
}

//this methods resets the best time for the current puzzle anc cut. set to 00.00 if cookie not found
function resetStats(){
	if (puzzleid != 0){
	if (document.getElementById('rotation').checked==true ) {rotation=5} else {rotation=0};
	if (rotation <1 ){
		var name = puzzleid + 'besttime'+img_cut;
	}
	else{
			var name = puzzleid + 'besttime'+img_cut + rotation;
	}
		var bestt = GetCookie(name);
		var bt = document.getElementById("besttime");
		if (bestt != null){
			bt.innerHTML = bestt;
		}
		else{// set to oo
			bt.innerHTML = "00:00";
		}
		var yt = document.getElementById("yourtime");
		yt.innerHTML = "00:00";
		// get the average and best time for this puzzle
	
		var theUrl = "ajax_getpuzzletimes.php?puzid=" + puzzleid + "&cutid=" + img_cut + "&rotation=" + rotation + "&ts=" + new Date().getTime();
		AjaxRequest.get(
  			{ 'url':theUrl,'onSuccess':function(req){ UpdatePuzzleTimes(req.responseXML,puzzleid,img_cut,rotation); }
  			}
		);
	
	}
}

/*
function initwatch(){
	var mydate = new Date();
	return((mydate.getTime() - clockStart)/1000);
}
*/
// changes the current puzzle this should reload the applet
function changePuzzle(tagid,cutid,isNotPerso,rotation){
	resetTimer();
	
	if(isNotPerso == 'true'){
		img_info = tagid + "/pinfo.txt";
		var rot = 0;
		if (rotation == -1){
			if(document.getElementById('rotation').checked == true){
				rot = 5;
			}
		}
		else
		{
			rot = rotation;
		}
		
	
	  AjaxRequest.get(
  	    { 'url':img_info,'onSuccess':function(req){ setPuzzle(req.responseText,tagid,isNotPerso,rot); }
  	  }
	  );
	  getCutName(cutid);
	}
	else{
		
		var pagename = document.getElementById("pageName");
		pagename.innerHTML = tagid;
		getCutName(cutid);
	}
}

// this is also called by clicking on an image in the gallery
// callback function that gets the puzzle id and stats and updates the page
function setPuzzle(res,tagid,isDir,rotation){
	var sp = res.split(";");
	puzzleid = sp[0];
	  	var pname = document.getElementById("puzname");
  	pname.innerHTML = sp[1];
  	var pagename = document.getElementById("pageName");
  	pagename.innerHTML = pname.innerHTML;
	if (sp[3]){
    puzColor = sp[3];
	}

	var psmall = document.getElementById("imgsmall");

	// sets new small image for the puzzle
 	psmall.src = tagid;
	if(isDir){
       psmall.src = psmall.src + "/image_small.jpg?";
    } 
    psmall.src = psmall.src + new Date().getTime();
	img_small = tagid + "/image_small.jpg";
	// set image name instead of the the date
  	var pname = document.getElementById("puzname");
  //	pname.innerHTML = document.getElementById(tagid).innerHTML;
  	var pagename = document.getElementById("pageName");
 // 	pagename.innerHTML = pname.innerHTML;
	
	img_big = tagid;
	if(isDir){
		img_big = img_big + "/image_big.jpg";
	}
	var rot = document.getElementById('rotation');
	if (rotation==0){
		rot.checked = false;
	}
	else
	{
		rot.checked = true;
	}
	generateAppletCode(img_big,ssid,img_cut,clip,rotation);
	
	
	googleAds();
	
	resetStats();
}

// callback function that gets the puzzle id and stats and updates the page
function setPuzzleBanner(res){
	var sp = res.split(";");
	puzzleid = sp[0];
	var pname = document.getElementById("puzname");
  	pname.innerHTML = sp[1];
  	var pagename = document.getElementById("pageName");
  	pagename.innerHTML = pname.innerHTML;
	if (sp[3])
	{
	  puzColor = sp[3];
	}
	
	var papplet = document.getElementById("puzzleapplet");
	var psmall = document.getElementById("imgsmall");

	// sets new small image for the puzzle
 	psmall.src = img_small + "?" + + new Date().getTime();
	// set image name instead of the the date
  	var pname = document.getElementById("puzname");
  //	pname.innerHTML = document.getElementById(tagid).innerHTML;
  	var pagename = document.getElementById("pageName");
  	//pagename.innerHTML = pname.innerHTML;

	var appid = document.getElementById("puzzle");
	// resets the time best time and avt times
	generateAppletCode(img_big,ssid,img_cut,clip);	
	resetStats();
}

function resetTimer(){
  if (t[2]) 
    pauseIt();
  t[3]=t[2]=t[1]=t[0]=0;
  var thistime = document.getElementById('yourtime');
	thistime.innerHTML ="00:00";
}

function myStartOver(){
	resetTimer();
	document.getElementById('puzzle').startOver();
	googleAds();
}

function setRotate(){ 
  resetTimer();
	
	if(document.getElementById('rotation').checked == true){
    document.getElementById('puzzle').setRotate(true);
  }
  else{
    document.getElementById('puzzle').setRotate(false);
  }
  resetStats();
}

function reshuffle(){
	document.puzzle.reshuffle();
}

function startCounter(){
	//startday = new Date();
	//clockStart = startday.getTime();
	//setTimeout('countup()',1)
	t[t[2]]=(new Date()).valueOf();
  t[2]=1-t[2];// switch states
  if (0==t[2]) {
    t[3]+=t[1]-t[0]; // do cumul of time
    t[1]=t[0]=0;
    countup();
  } 
  else {
    setInterval('countup()', 43);
  }
}

function pauseIt(){
  t[t[2]]=(new Date()).valueOf();
  t[2]=1-t[2];// switch states
  if (0==t[2]) {
    t[3]+=t[1]-t[0]; // do cumul of time
    t[1]=t[0]=0;
    countup();
    document.getElementById('puzzle').setPause(true);
  } 
  else {
    setInterval('countup()', 43);
    document.getElementById('puzzle').setPause(false);
  }
}


// set the current time as best time for client. also set puzzle best time if time is better
function setAsBestTime(){
	var thistime = document.getElementById('yourtime')
	var bestime = document.getElementById('besttime')
	var bigtime = document.getElementById('bigtime')
	
	bestime.innerHTML = thistime.innerHTML
	
	var bigm = bigtime.innerHTML.split(":")
	var mym = thistime.innerHTML.split(":")
	if (mym[0] < bigm[0]){
		bigtime.innerHTML = thistime.innerHTML
		// tell the applet to update the puzzle best time
	}
	else {
		if (mym[0] == bigm[0]){
		// look at the seconds
			if (mym[1] < bigm[1]){
				bigtime.innerHTML = thistime.innerHTML
				// tell the applet to update the puzzle best time
			}
		}
	}
}

//this stops the counter and stores the cookie info if that is the best score for this puzzle
function stopCounter(){	
	t[2]=0;
	var thistime = document.getElementById('yourtime')
	currenturl = document.location.href;
	
	var pos_lang=currenturl.indexOf("ext");
	if (document.getElementById('rotation').checked== true ) {rotation=5} else {rotation=0};

	if (pos_lang > 0){
	}
    else{
      saveNewTime(thistime.innerHTML,puzzleid,img_cut,rotation);
    }
	var cookiename;
	if (rotation < 1){
		cookiename = puzzleid + 'besttime' + img_cut;
	}
	else{
		cookiename = puzzleid + 'besttime' + img_cut + rotation;
	}

	var bestt = GetCookie(cookiename);
	if (bestt != null){
		// check if new time is better
		var thismins = thistime.innerHTML.split(":")
		var bmins = bestt.split(":")
		if (thismins[0] < bmins[0]){
			// new time is better save it

			SetCookie(cookiename,thistime.innerHTML,exp)
			setAsBestTime()
		}
		else{
			if (thismins[0] == bmins[0]){
			// check seconds
				if (thismins[1] < bmins[1]){
					SetCookie(cookiename,thistime.innerHTML,exp)
					setAsBestTime()
				}
			}
		}
	}
	else{
		SetCookie(cookiename,thistime.innerHTML,exp)
		setAsBestTime()
	}
	// tells the applets to save this new time for this puzzle
//	document.puzzle.updateTimes(puzzleid,thistime.innerHTML);
  
}

function countup(){
	if (t[2]){
    t[1]=(new Date()).valueOf();
		var counter=document.getElementById("yourtime");
		var tSecs = Math.round((t[3]+t[1]-t[0]) / 1000); 
   	var iSecs = tSecs % 60;
   	var iMins = Math.round((tSecs-30)/60);  
		var sSecs;
		if (iSecs > 9)
			sSecs = iSecs;
		else
			 sSecs = "0" + iSecs;
		var sMins;
   		if (iMins > 9) 
			sMins =  iMins ;
		else
			sMins =  "0" + iMins;
   
		counter.innerHTML = "" + sMins + ":" + sSecs;
   	//setTimeout('countup()',1000); 
	}
}


function setPuzzleHistory1(text){
	setPuzzleHistory("day1",text);
}
function setPuzzleHistory2(text){
	setPuzzleHistory("day2",text);
}
function setPuzzleHistory3(text){
	setPuzzleHistory("day3",text);
}
function setPuzzleHistory4(text){
	setPuzzleHistory("day4",text);
}
function setPuzzleHistory5(text){
	setPuzzleHistory("day5",text);
}
// sets puzzle name for the last 5 days in history navigation
function setPuzzleHistory(tagid,res){
	var d1 = document.getElementById(tagid);
	var sp = res.split(";");
	d1.innerHTML = sp[1];
}

// sets the puzzle id and name
function setPuzzleInfo(res,rotation){
	var pname = document.getElementById("puzname");
	var pn = document.getElementById("pageName");
  var sp = res.split(";");
	puzzleid = sp[0];
	puzzleName = sp[1];
	if (res.size > 3){
	 puzColor=sp[3];
	}
	pname.innerHTML = sp[1];
	pn.innerHTML=sp[1];
	// added by Nat 5/30/06 test
	var rot = document.getElementById('rotation');
	if (rotation == 0){
		rot.checked = false;
	}
	else
	{
		rot.checked = true;
	}
	generateAppletCode(img_big,ssid,img_cut,clip,rotation);
	resetStats();
}

function setApplet(){
	generateAppletCode(img_big,ssid,img_cut,clip);
	resetStats();
}
function autoSolve(){
//	document.puzzle.autoSolve();
}

function noAdd(){
	document.getElementById('googleads').innerHTML = "<img src=\"images/JigKids2.jpg\"/>";
	to = setTimeout("nextAd()", 10000);
}

function addAdbrite(myhtml){
	document.getElementById('googleads').innerHTML = myhtml;
}

function getAdbrite(){
			AjaxRequest.get(
			{ 
				'url':'addbr.html',
				'onSuccess':function(req){ addAdbrite(req.responseText);},
				'timeout':5000,
   				'onTimeout':function(){ noAdd();},
				'onError':function(){ noAdd();}
			}
		);
}

function loadBanner(xml){
    var html_content = xml.getElementsByTagName('content_ban').item(0).firstChild.nodeValue;
    var reload_after = xml.getElementsByTagName('reload').item(0).firstChild.nodeValue;
    document.getElementById('googleads').innerHTML = html_content;
	var ifr = document.getElementById('GoogleAds1');
	//googleAds();
	adBrite();
    try {
        clearTimeout(to);
    } catch (e) {}

    to = setTimeout("nextAd()", parseInt(reload_after));
}

function googleAds(){
	var ifr = document.getElementById('GoogleAds1');
	if(ifr){
		document.getElementById('googleads').innerHTML = goog;
	}
}

function adBrite(){
	var ifr2 = document.getElementById('AddBr');
	if(ifr2){
		getAdbrite();
	}
}

function nextAd()
{
    var now = new Date();
    var url = 'ajax-banner.php?ts=' + now.getTime();
	AjaxRequest.get(
		{ 
			'url':url,
			'onSuccess':function(req){ loadBanner(req.responseXML); },
			'timeout':2000,
 			'onTimeout':function(req){ noAdd();},
			'onError':function(req){ noAdd();}
		}
	);
	adBrite();
}

// stores language in a cookie
function setLanguage(lg)
{
	// expiration for the creation of cookies
     var expDays = 90;
     var exp = new Date(); 
     exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
	 var cookiename="lang";
	
	 SetCookie(cookiename,lg,exp);
	 currenturl = document.location.href;
	 var pos_lang=currenturl.indexOf("lang");
	 if (pos_lang > 0)
	 {
		 var firstpart=currenturl.substring(0,pos_lang+ 5);
		
		 var secondpart=currenturl.substring(pos_lang + 7);
		
		 location.href=firstpart + lg + secondpart;
	 }
	 
	 else
	 {
		var cur=currenturl.indexOf("?");

		if (cur > 0)
		{
			// there are parameters but not lang, add lang to the list of params
			var new_url=currenturl + "&lang=" + lg;
			location.href = new_url;	
		}
		else
		{
			// no params in url
			var new_url = currenturl + "?lang=" + lg;
          location.href= new_url;
		 
		}
	 }
}

function showTop35(){
document.getElementById('top35').style.display='';
document.getElementById('leastplayed').style.display='none';
document.getElementById('mostplayed').style.display='none';
}

function showLeastPlayed(){
document.getElementById('top35').style.display='none';
document.getElementById('leastplayed').style.display='';
document.getElementById('mostplayed').style.display='none';
	
}
function showMostPlayed(){
document.getElementById('top35').style.display='none';
document.getElementById('leastplayed').style.display='none';
document.getElementById('mostplayed').style.display='';
	
}