// fixme: repeated from other js file, belongs in common lib

// to prevent possible IE innerHTML bugs. solution
// suggested by Toby Cole: http://domscripting.com/blog/display/99
function appendInnerHTML(outputFld, theHtml) {
	//alert("in appendInnerHTML");
	var newdiv = document.createElement("div");
	newdiv.innerHTML = theHtml;
	fld = document.getElementById(outputFld);
	deleteChildren(fld);
	fld.appendChild(newdiv);
}

function appendInnerHTMLnoDelete(outputFld, theHtml) {
	//alert("in appendInnerHTML");
	var newdiv = document.createElement("div");
	newdiv.innerHTML = theHtml;
	fld = document.getElementById(outputFld);
	fld.appendChild(newdiv);
}

function appendMsg(nodeId, msg) {
	node = document.getElementById(nodeId);
	while (node.hasChildNodes()) {
		node.removeChild(node.firstChild);
	}
	var textNode = document.createTextNode(msg);
	node.appendChild(textNode);
}


function deleteChildren(node) {
	while (node.hasChildNodes()) {
		node.removeChild(node.firstChild);
	}
}

function ajaxLogin() {
	var ajaxRequest;

	// rewritten to work with apache rewriting
	var URL = unescape(location.href);
	//var tmp = URL.substring(URL.lastIndexOf("/")+1);
	//var currentPage = tmp.substring(0, tmp.indexOf("."));
	//if (currentPage == "watch") { var isPlayerPage = true; }
	var pos = URL.indexOf("/watch/");
	if (pos > 0) {
		var currentPage = "watch";
	}

	try {
		ajaxRequest = getAjaxRequest();
	} catch (e) {
		return -1;
	}

	// fixme: these should really be arguments to the function, of course
	// username = document.forms.loginForm2.username2.value;
	// password = document.forms.loginForm2.password2.value;
	username = document.forms.loginform.username.value;
	password = document.forms.loginform.password.value;
	errorFld = "info";
	//successFld = "topBar";
	// fixme: same as in topField on server side. not pretty to have multiple
	// variables with the same content, but don't know what else to do here...
	//topBarHtml = "<td>You are logged in as "+username+". </td><td><a href='http://www.animasher.com/member/'>Your page</a><td><a href='http://www.animasher.com/logout/'>Logout</a>";
	//var successNode = document.getElementById('topBar');

	if (username == "") {
		appendMsg(errorFld, SUPPLY_USERNAME);
		return false;
	}
	if (password == "") {
		appendMsg(errorFld, SUPPLY_PASSWORD);
		return false;
	}

	ajaxRequest.onreadystatechange = function() {
		if (ajaxRequest.readyState == 4) {
			if (ajaxRequest.status == 200) {
				//if (ajaxRequest.responseText == "OK") {
				//if (ajaxRequest.responseText.substring(0, 5) == "user=") {
				// res is on the form: "news=num.username=name"
				var res = ajaxRequest.responseText;
				if (res.substring(0, 5) == "news=") {
					var delimPos = res.indexOf(".");
					var numNews = res.substring(5, delimPos);
					var username = res.substring(delimPos+("user=".length)+1);
					var tempname=username;
					if (username.length>12){
						tempname="";
					}
					/* redo */

					//appendMsg('userNews', numNews);
					//appendMsg('showUsernameFld', username);
					
					if (numNews > 0) {
						appendMsg('welcomeMsg1', HI + tempname+ '!');
						
						appendMsg('welcomeMsg2', NEW_MSGS.replace(/NUMBER/,numNews));
					} else {
						appendMsg('welcomeMsg1', WELCOME + tempname + HAVE_Y_BACK);
					}

					expand('lg1', null);
					expand('lg2', null);
					
					if (currentPage == "watch") {
						styleObj=document.getElementById("commentapprove").style;
	   					styleObj.display='';
	   					styleObj=document.getElementById("commentunapprove").style;
	   					styleObj.display='none';
					}
					
					/* to here */

					//loginTopBar(successNode, currentPage, username);
					//alert("currentPage: "+currentPage);
					//alert("response OK");
					if (currentPage == "watch") {
						//alert("current page is watch");
						//not needed when anon comments allowed
						//allowComments();
					}
				} else {
					alert(ajaxRequest.responseText);
					//appendMsg(errorFld, ajaxRequest.responseText);
				}
			} else {
				alert(LOGIN_ERROR);
				//msg(errorFld, "ajaxRequest returned status code "+ajaxRequest.status); // fixme: some error msg here? or just leave user oblivious for now?
			}
		}
	}
	ajaxRequest.open("POST", "http://www.animasher.com/comm/ajax_controller.php", true);
	ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	//alert("ajax POST: " + "login=true&username="+username+"&password="+password);
	ajaxRequest.send("login=true&username="+username+"&password="+hex_sha1(password));

	return false;
}

function ajaxGetAnimations(page, outputFld, criteria) {
	var numOfAnimations = 5;
	var offset = (page+1) * numOfAnimations; //var offset = page * numOfAnimations;
	var ajaxRequest;

	try {
		ajaxRequest = getAjaxRequest();
	} catch (e) {
		return -1;
	}

	ajaxRequest.onreadystatechange = function() {
		if (ajaxRequest.readyState == 4) {
			if (ajaxRequest.status == 200) {
				//alert(ajaxRequest.responseText.substring(0, 15));
				if (ajaxRequest.responseText.substring(0, 4) == "ok. ") {
					//alert("response ok: " + ajaxRequest.responseText.substring(4));
					appendInnerHTML(outputFld, ajaxRequest.responseText.substring(4));
				} else if (ajaxRequest.responseText.substring(0, 9) == "popular. ") {
					appendInnerHTML(outputFld, ajaxRequest.responseText.substring(9));
					pop_page = 0;
				} else if (ajaxRequest.responseText.substring(0, 8) == "recent. ") {
					appendInnerHTML(outputFld, ajaxRequest.responseText.substring(8));
					recent_page = 0;
				} else if (ajaxRequest.responseText.substring(0, 5) == "hot. ") {
					appendInnerHTML(outputFld, ajaxRequest.responseText.substring(5));
					hot_page = 0;
				} else if (ajaxRequest.responseText.substring(0, 9) == "related. ") {
					appendInnerHTML(outputFld, ajaxRequest.responseText.substring(9));
					rel_page = 0;
				} else if (ajaxRequest.responseText.substring(0, 9) == "nothing. ") {
					//alert("we had nothing");
				} else {
					// FIXME
					alert(ajaxRequest.responseText.substring(0, 1));
					// alert("There was some random error. Sorry about that!");
					//appendMsg(errorFld, ajaxRequest.responseText);
				}
			} else {
				alert(WOOPS_BAD_SERVER);
			}
		}
	}

	ajaxRequest.open("POST", "http://www.animasher.com/comm/ajax_controller.php", true);
	ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	ajaxRequest.send("getSidescrollingAnimations=true&criteria="+criteria+"&offset="+offset+"&numOfAnimations="+numOfAnimations);

	return false;
}

// putting this here too, to reduce latency

/*
* A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
* in FIPS PUB 180-1
* Version 2.1a Copyright Paul Johnston 2000 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for details.
*/

/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
function hex_sha1(s){return binb2hex(core_sha1(str2binb(s),s.length * chrsz));}
function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * chrsz));}
function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length * chrsz));}
function hex_hmac_sha1(key, data){ return binb2hex(core_hmac_sha1(key, data));}
function b64_hmac_sha1(key, data){ return binb2b64(core_hmac_sha1(key, data));}
function str_hmac_sha1(key, data){ return binb2str(core_hmac_sha1(key, data));}

/*
* Perform a simple self-test to see if the VM is working
*/
function sha1_vm_test()
{
	return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
}

/*
* Calculate the SHA-1 of an array of big-endian words, and a bit length
*/
function core_sha1(x, len)
{
	/* append padding */
	x[len >> 5] |= 0x80 << (24 - len % 32);
	x[((len + 64 >> 9) << 4) + 15] = len;

	var w = Array(80);
	var a =  1732584193;
	var b = -271733879;
	var c = -1732584194;
	var d =  271733878;
	var e = -1009589776;

	for(var i = 0; i < x.length; i += 16)
	{
		var olda = a;
		var oldb = b;
		var oldc = c;
		var oldd = d;
		var olde = e;

		for(var j = 0; j < 80; j++)
		{
			if(j < 16) w[j] = x[i + j];
			else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
			var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
			safe_add(safe_add(e, w[j]), sha1_kt(j)));
			e = d;
			d = c;
			c = rol(b, 30);
			b = a;
			a = t;
		}

		a = safe_add(a, olda);
		b = safe_add(b, oldb);
		c = safe_add(c, oldc);
		d = safe_add(d, oldd);
		e = safe_add(e, olde);
	}
	return Array(a, b, c, d, e);

}

/*
* Perform the appropriate triplet combination function for the current
* iteration
*/
function sha1_ft(t, b, c, d)
{
	if(t < 20) return (b & c) | ((~b) & d);
	if(t < 40) return b ^ c ^ d;
	if(t < 60) return (b & c) | (b & d) | (c & d);
	return b ^ c ^ d;
}

/*
* Determine the appropriate additive constant for the current iteration
*/
function sha1_kt(t)
{
	return (t < 20) ?  1518500249 : (t < 40) ?  1859775393 :
	(t < 60) ? -1894007588 : -899497514;
}

/*
* Calculate the HMAC-SHA1 of a key and some data
*/
function core_hmac_sha1(key, data)
{
	var bkey = str2binb(key);
	if(bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);

	var ipad = Array(16), opad = Array(16);
	for(var i = 0; i < 16; i++)
	{
		ipad[i] = bkey[i] ^ 0x36363636;
		opad[i] = bkey[i] ^ 0x5C5C5C5C;
	}

	var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
	return core_sha1(opad.concat(hash), 512 + 160);
}

/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y)
{
	var lsw = (x & 0xFFFF) + (y & 0xFFFF);
	var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
	return (msw << 16) | (lsw & 0xFFFF);
}

/*
* Bitwise rotate a 32-bit number to the left.
*/
function rol(num, cnt)
{
	return (num << cnt) | (num >>> (32 - cnt));
}

/*
* Convert an 8-bit or 16-bit string to an array of big-endian words
* In 8-bit function, characters >255 have their hi-byte silently ignored.
*/
function str2binb(str)
{
	var bin = Array();
	var mask = (1 << chrsz) - 1;
	for(var i = 0; i < str.length * chrsz; i += chrsz)
		bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - i%32);
	return bin;
}

/*
* Convert an array of big-endian words to a string
*/
function binb2str(bin)
{
	var str = "";
	var mask = (1 << chrsz) - 1;
	for(var i = 0; i < bin.length * 32; i += chrsz)
		str += String.fromCharCode((bin[i>>5] >>> (32 - chrsz - i%32)) & mask);
	return str;
}

/*
* Convert an array of big-endian words to a hex string.
*/
function binb2hex(binarray)
{
	var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
	var str = "";
	for(var i = 0; i < binarray.length * 4; i++)
	{
		str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
		hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8  )) & 0xF);
	}
	return str;
}

/*
* Convert an array of big-endian words to a base-64 string
*/
function binb2b64(binarray)
{
	var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
	var str = "";
	for(var i = 0; i < binarray.length * 4; i += 3)
	{
		var triplet = (((binarray[i   >> 2] >> 8 * (3 -  i   %4)) & 0xFF) << 16)
		| (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 )
		|  ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);
		for(var j = 0; j < 4; j++)
		{
			if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
			else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
		}
	}
	return str;
}

/* graphic functions by MJ */
function expand(thistag, thisarrow) {
   if (document.getElementById(thistag)==null) {
	return;
   }
   styleObj=document.getElementById(thistag).style;
   if (styleObj.display=='none') {
   	styleObj.display='';
	if(thisarrow!=null && thisarrow!="null") switchImage(thisarrow, "/images/smallarrow_down.gif");
	//tag.innerHTML = "Click here to hide";
   } else {
   	styleObj.display='none';
	if(thisarrow!=null && thisarrow!="null") switchImage(thisarrow, "/images/smallarrow.gif");
    //tag.innerHTML = "Click here to show";
   }
}

/* animationthumb-movement functions */
var stepsDone = 0;
var duration = 10;
var framespeed = 50;
var dblBlk=0;

function appendInnerHTML(outputFld, theHtml) {
	var newdiv = document.createElement("div");
	newdiv.innerHTML = theHtml;
	fld = document.getElementById(outputFld);
	deleteChildren(fld);
	fld.appendChild(newdiv);
}


var div0;
var div1;

var myType="";
var pagenum=0;

var pop_page=1;
var recent_page=1;
var hot_page=1;
var rel_page=1;


function doMove(target){
    if (dblBlk==1) return;
	dblBlk=1;
	styleObj=document.getElementById(target).style;

	//currentStep, startPos, endPos, totalSteps
	curPos=	easeOut(stepsDone, 0, -760, duration);
	styleObj.left=curPos+"px";
	if (stepsDone <duration) {
		stepsDone++;
		setTimeout("doMove('"+target+"')",framespeed)
   		dblBlk=0;
	} else {
		stepsDone = 0;
        styleObj.left="0px";
        //switch divs
        //var temp1 = document.getElementById(div0).innerHTML
  		appendInnerHTML(div0,document.getElementById(div1).innerHTML);
        //appendInnerHTML(div1,temp1);

   		ajaxGetAnimations(pagenum,div1,myType);
        dblBlk=0;
	}
	return false;
}
function getMoreAnims(type) {
	myType=type;
	if (type == 'popular') {
    	div0='pop0';
      	div1='pop1';
        pagenum=pop_page;
        pop_page++;
        doMove('popcont');
    } else if (type == 'recent') {
    	div0='rec0';
      	div1='rec1';
        pagenum=recent_page;
        recent_page++;
        doMove('reccont');
    } else if (type == 'hot') {
        div0='hot0';
      	div1='hot1';
        pagenum=hot_page;
        hot_page++;
        doMove('hotcont');
    } else if (type == 'related') {
        div0='rel0';
      	div1='rel1';
        pagenum=rel_page;
        rel_page++;
        doMove('relcont');
    }
}
function easeOut(t, b,c, d){
		return -c * (t /= d) * (t - 2) + b;
}
function easeInOut(t, b,c, d) {
		if ((t /= d / 2) < 1)
			return c / 2 * t * t + b;

		return -c / 2 * ((--t) * (t - 2) - 1) + b;
	}


function setCookie(name, value, daysToexpiry, path, domain, secure){
var today = new Date();
today.setTime( today.getTime() );
if ( daysToexpiry ) daysToexpiry= daysToexpiry * 1000 * 60 * 60 * 24;
var expires_date = new Date(today.getTime() + (daysToexpiry));
document.cookie = name + "=" +escape(value) +
((daysToexpiry) ? ";expires=" + expires_date.toGMTString():"")+
((path)? ";path=" + path : "" ) +
((domain) ? ";domain=" + domain : "" ) +
((secure) ? ";secure" : "" );
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


function setLang(lang){
	setCookie("locale",lang,"/");
	window.location.reload();
	return false;
}

//Search and login-fields clearing of text when clicked, and border
$(document).ready(function(){
    $("input.idle, textarea.idle").focus(function(){
            $(this).addClass("activeField").removeClass("idle");
            if (!$(this).hasClass("hasBeenCleared")) {
            	$(this).val("");
            	$(this).addClass("hasBeenCleared");
            }
    }).blur(function(){
            $(this).removeClass("activeField").addClass("idle");
    });
});

$(function(){
    $("#BGSelector").click(function() {
		var inum = (Math.floor(Math.random()*150));
		var u = "http://static1.animasher.com/resources/STATICS/BKGS/" + inum + ".jpg"; 
        $("body").css("background-image", "url('"+u+"')");
        $("html").css("background-image", "url('"+u+"')");
		setCookie("bkg",inum, "/");
		//document.cookie="bkg="+inum+";expires="+new Date(new Date().getTime()+86400000).toGMTString();
    });
});