// Z-index global
var oZI = 10;

// machine ou domaine qui héberge l'application, shuowenjiezi.com
var myHost = location.host;

// récupération des coordonnées de la souris
var IE = document.all?true:false;
if (!IE) document.addEventListener("mousemove", getMouseXY, true);
document.onmousemove = getMouseXY;
var tempX = 0;
var tempY = 0;





Array.prototype.in_array = function(p_val) {
    for (var i = 0, l = this.length; i < l; i++) {
        if (this[i] == p_val) {
            rowid = i;
            return true;
        }
    }
    return false;
}
 




function getMouseXY(e) {
	if (IE) {
		// grab the x-y pos.s if browser is IE
		tempX = event.clientX + document.body.scrollLeft;
		tempY = event.clientY + document.body.scrollTop;
	} else {
		// grab the x-y pos.s if browser is NS
		tempX = e.pageX;
		tempY = e.pageY;
	}
	if (tempX < 0) tempX = 0;
	if (tempY < 0) tempY = 0;
	return true;
}

function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent)
		while(1) {
			curleft += obj.offsetLeft;
			if (!obj.offsetParent)
				break;
		obj = obj.offsetParent;
		}
	else if(obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	if(obj.offsetParent)
		while(1) {
			curtop += obj.offsetTop;
			if(!obj.offsetParent)
				break;
			obj = obj.offsetParent;
		}
	else if(obj.y)
		curtop += obj.y;
	return curtop;
}

function showDIV(myID) {
    document.getElementById(myID).style.visibility = "visible";
    document.getElementById(myID).style.display = "block";
}

function hideDIV(myID) {
    document.getElementById(myID).style.visibility = "hidden";
    document.getElementById(myID).style.display = "none";
}





function chWindow(unicode, language, x, y) {
	// si les coordonnées d’affichage ne sont pas définies
	if (x == undefined) x = tempX;
	if (y == undefined) y = tempY;

	// id de la fenêtre pour la manipulation
	var n = 0;
	var id = 'w' + n + '';
	while ($('#' + id).length) {
		n++;
		id = 'w' + n + '';
	}
	
	// id complet de la fenêtre pour la mémorisation...
	var wid = 'character-' + unicode;
	
	// alert("id : " + id + "\n" + "wid : " + wid);

	// si la fenêtre demandée n’existe pas déjà
	oldid = iWindowExists(wid);
	if (oldid) {
		iWindowDisplay('w' + oldid, x, y);
		return;
	}
	
	// construction de la fenêtre
	var title = '&#' + new hex(unicode).toDecimal() + ';';
	var div = document.createElement('div');
	div.className = 'jqDnR';
	div.id = id;
	
	document.getElementById('pageContent').appendChild(div);

	// écriture du contenu de la fenêtre
	var HTML = '';
	HTML += '<div class="jqHandle jqDrag jqTitle" onmousedown="iWindowTop(\'' + id + '\');">';
	HTML += '	<input type="hidden" id="' + id + '-wid" value="' + wid + '" />';
	HTML += '	<span class="chinese" id="' + id + '-title">' + title + '</span>';
	HTML += '	<div class="jqClose"><a href="javascript:iWindowClose(\'' + id + '\');" />×</a></div>';
	HTML += '</div>';
	// HTML += '<div class="jqHandle jqResize"></div>';
	HTML += '<div class="jqContent" id="' + id + '-content" onmousedown="iWindowTop(\'' + id + '\');">';
	HTML += '<center><img src="/graphics/ajax-loader-1.gif" style="margin: 11px" />';
	HTML += '</div>';

	// remplissage de la fenêtre
	// $('#' + id).html(HTML);
	document.getElementById(id).innerHTML = HTML;

	// $('#' + myID).jqDrag('.jqDrag').jqResize('.jqResize');
	$('#' + id).jqDrag('.jqDrag');

	// ajout de l'ID dans la liste des fenêtres pour une mémorisation éventuelle
	iWindowPush(n, wid);
	
	// affichage de la fenêtre
	iWindowDisplay(id, x, y);

	// URL de la requête AJAX
	var url = 'http://www.shuowenjiezi.com/ajax/char.php';
	var data = 'unicode=' + unicode + '&lang=' + language + '&x=' + x + '&y=' + y;

	// requête AJAX
	$.ajax({
		type: 'GET',
		url: url,
		data: data,
		success: function(html) { $('#' + id + '-content').html(html); },
		error: function() { alert('le serveur n’a pu être contacté, assurez-vous que vous êtes bien connecté(e) à internet'); }
	});
}





function stWindow(unicode, data, value, language, x, y) {
	// si les coordonnées d’affichage ne sont pas définies
	if (x == undefined) x = tempX;
	if (y == undefined) y = tempY;

	// id de la fenêtre pour la manipulation
	var n = 0;
	var id = 'w' + n + '';
	while ($('#' + id).length) {
		n++;
		id = 'w' + n + '';
	}

	// id complet de la fenêtre pour la mémorisation...
	var wid = 'standard-' + unicode + '-' + data;

	// ...et cas particulier pour les fenêtres qui ont le même “data”
	if (value != '' && value != 'null') {
		value = str_replace('.', '_', value);
		var wid = wid + '-' + value;
	}

	// si la fenêtre demandée n’existe pas déjà
	oldid = iWindowExists(wid);
	if (oldid) {
		iWindowDisplay('w' + oldid, x, y);
		return;
	}

	// construction de la fenêtre
	var title = 'title';
	var div = document.createElement('div');
	div.className = 'jqDnR';
	div.id = id;
	
	document.getElementById('pageContent').appendChild(div);

	// écriture du contenu de la fenêtre
	var HTML = '';
	HTML += '<div class="jqHandle jqDrag jqTitle" onmousedown="iWindowTop(\'' + id + '\');">';
	HTML += '	<input type="hidden" wid="' + id + '" value="' + wid + '" />';
	HTML += '	<span class="chinese" id="' + id + '-title">' + title + '</span>';
	HTML += '	<div class="jqClose"><a href="javascript:iWindowClose(\'' + id + '\');" />×</a></div>';
	HTML += '</div>';
	// HTML += '<div class="jqHandle jqResize"></div>';
	HTML += '<div class="jqContent" id="' + id + '-content" onmousedown="iWindowTop(\'' + id + '\');">';
	HTML += '<center><img src="/graphics/ajax-loader-1.gif" style="margin: 11px" />';
	HTML += '</div>';

	// remplissage de la fenêtre
	// $('#' + id).html(HTML);
	document.getElementById(id).innerHTML = HTML;

	// $('#' + myID).jqDrag('.jqDrag').jqResize('.jqResize');
	$('#' + id).jqDrag('.jqDrag');

	// ajout à la liste des fenêtres en cours pour une mémorisation éventuelle
	iWindowPush(n, wid);
	
	// affichage de la fenêtre
	iWindowDisplay(id, x, y);

	// URL de la requête AJAX
	var url = "http://www.shuowenjiezi.com/ajax/services.php";
	var parameters = "unicode=" + unicode + "&data=" + data + "&value=" + value + "&language=" + language + "&x=" + x + "&y=" + y;

	// alert(url + '?' + parameters);
	$.ajax({
		type: "GET",
		url: url,
		data: parameters,
		success: function(html) {
			// éclatement des données : title | content
			var tmp = new Array();
			tmp = html.split("|");
			$('#' + id + '-title').html(tmp[0]);
			$('#' + id + '-content').html(tmp[1]);
		},
		error: function() { alert("le serveur n’a pu être contacté, assurez-vous que vous êtes bien connecté(e) à internet"); }
	});
}





function iModal()
{
	// récupération d'un ID disponible
	var myID = "modal_1";
	var number = 1;
	while (document.getElementById(myID)) {
		number++;
		myID = "modal_" + number;
	}
	
	// création du DIV conteneur
	var myDIV = document.createElement("DIV");
	myDIV.className = "modal";
	myDIV.id = myID;
	myDIV.style.zIndex = "100000";

	document.getElementById("pageContent").appendChild(myDIV);

	// écriture du contenu de la fenêtre
	var HTML  = '<div class="modalTitle">Attention</div>';
	HTML += '<div class="modalContent">Une erreur s’est encore produite, blah blah blah, vérifiez que votre ordinateur est connecté à internet, blah blah blah...</div>';

	myDIV.innerHTML = HTML;

	// affichage de la fenêtre
    document.getElementById(myID).style.top = 300 + "px";
    document.getElementById(myID).style.left = 400 + "px";

	$("#" + myID).fadeIn("fast");

    document.getElementById(myID).style.visibility = "visible";
    document.getElementById(myID).style.display = "block";

	// $('#' + myID).css({ zIndex: 1000000 });
}

function iWindowDisplay(id, x, y) {
	// correction des coordonnées
	var xPos = parseInt(x) + 7;
	var yPos = parseInt(y) + 17;
	
    document.getElementById(id).style.top = yPos + 'px';
    document.getElementById(id).style.left = xPos + 'px';

	$('#' + id).fadeIn('fast');

    document.getElementById(id).style.visibility = 'visible';
    document.getElementById(id).style.display = 'block';

    iWindowTop(id);
}

function iWindowTop(id) {
	// incrémentation du z-index global
	oZI++;
	$('#' + id).css({ zIndex: oZI });
}

function iWindowPush(n, wid) {
		wList[n] = wid;
		var html = 'liste des fenêtres : \n';
		for (var i = 0; i < wList.length; i++) {
			html += '[' + i + '] : ' + wList[i] + '\n';
		}
}

function iWindowExists(wid) {
	for (var n = 0; n < wList.length; n++) {
		if (wList[n] == wid) return n.toString();
	}
	return false;
}

function iWindowClose(id) {
	$('#' + id).fadeOut('fast');
	// $('#' + id).css('visibility', 'hidden');
	// $('#' + id).css('display', 'none');
}



function sNow2(myType) {
	if (!document.getElementById("sWindow")) {
		HTML  = '<div id="sWindow" class="jqDnR" style="display: block; visibility: visible;" onmousedown="iWindowTop(\'sWindow\');">';
		HTML += '<div id="sTitle" class="jqDrag jqHandle" onmousedown="iWindowTop(\'sWindow\');"><a href="javascript:sClose2();">×</a></div>';
		HTML += '<iframe id="sFrame" frameborder="0"></iframe>';
		HTML += '</div>';
		
		var tmp = document.createElement("div");
		tmp.style.zIndex = oZI;
		tmp.innerHTML = HTML;
		document.getElementById("pageContent").appendChild(tmp);
	}

	$("#sWindow").css('top', $(window).height()/2 - $("#sWindow").height()/2);
	$("#sWindow").css('left', $(window).width()/2 - $("#sWindow").width()/2); 		
	$("#sWindow").fadeIn("fast");
	$('#sWindow').jqDrag('.jqDrag');

	iWindowTop("sWindow");

	// partie pour IE à améliorer !
	if (BrowserDetect.browser == "Firefox") document.getElementById("sFrame").contentDocument.location.href = "/components/s3.php?what=" + myType;
	else document.getElementById("sFrame").contentWindow.location.href = "/components/s3.php?what=" + myType;
}

function sClose2()
{
	$("#sWindow").fadeOut("fast");
	$(window).focus();
}




function sNow(sType)
{
	if (!document.getElementById("myFog"))
	{
		myFog = document.createElement("DIV");
		myFog.id = "myFog";
		myFog.className = "fog";
		document.body.appendChild(myFog);
		myFog.innerHTML += '<br /><br /><br /><br /><div style="background-color: #fff; width: 700px; margin: 0 auto; text-align:right;"><a style="font-size: 19px; font-weight: bold; text-decoration: none; padding-right: 4px;" href="javascript:sClose();">×</a></div>';

		myFrame = document.createElement("IFRAME");
		// myFrame.setAttribute("src", "/components/s.php?what=page");
		myFrame.style.width = "700px";
		myFrame.style.height = "300px";
		myFrame.style.backgroundColor = "white";
		myFrame.id = "myS";
		myFrame.style.position = "relative";
		document.getElementById("myFog").appendChild(myFrame);

	}

	// cas particulier “bishun”
	if (sType == "bishun") myFrame.style.height = "520px";

	// partie pour IE à améliorer !
	if (BrowserDetect.browser == "Firefox") document.getElementById("myS").contentDocument.location.href = "/components/s.php?what=" + sType;
	else document.getElementById("myS").contentWindow.location.href = "/components/s.php?what=" + sType;


	$("#myFog").fadeIn("fast");
	document.getElementById("myFog").style.visibility = "visible";
	document.getElementById("myFog").style.display = "block";

}

function sClose()
{
	document.getElementById("myFog").style.visibility = "hidden";
	document.getElementById("myFog").style.display = "none";
}




function toLanguage(code)
{
	document.getElementById("lang").value = code;
	document.getElementById("langForm").submit();
}



// liste des fenêtres créées dans la page courante
var wList = new Array();

function memoWindowPos() {
	var posX = 0;
	var posY = 0;
	var wData = '';
	var id = document.getElementById('thisPageID').value;
	var user = document.getElementById('thisUserID').value;

	for (var i = 0; i < wList.length; i++) {
		// alert(document.getElementById('w' + i).style.display);
		if (document.getElementById('w' + i).style.display != 'none') {
			posX = findPosX(document.getElementById('w' + i)) - 7;
			posY = findPosY(document.getElementById('w' + i)) - 17;

			if (wData != '') wData += '|';
			wData += wList[i] + ',' + posX + ',' + posY;
		}
	}

	var url = 'http://' + myHost + '/ajax/window.php';
	var parameters = 'user=' + user + '&id=' + id + '&do=record&data=' + wData + '&nocache=' + Math.random();

	// alert(url + '?' + parameters);

	$.ajax({
		type: 'GET',
		url: url,
		data: parameters,
		success: function(HTML) {
   			if (HTML == 'OK') alert("OK, the windows have been saved!"); /*$('#sBar').updateStatus('ok', 'les fenêtres ont été mémorisées');*/
   			else alert("ERROR, the windows have not been saved!");
   		},
		error: function() {
			alert('le serveur n’a pu être contacté, assurez-vous que vous êtes bien connecté(e) à internet');
		}
	});
}

function forgetWindowPos()
{
	var id = document.getElementById('thisPageID').value;
	var user = document.getElementById('thisUserID').value;
	var myURL = "http://" + myHost + "/ajax/window.php";
	var myData = "user=" + user + "&id=" + id + "&do=delete" + "&nocache=" + Math.random();
	// alert(myURL + "?" + myData);
	
	$.ajax({
		type: "GET",
		url: myURL,
		data: myData,
		success: function(HTML) {
			// alert(HTML);
   			if (HTML == "OK") alert("OK, the saved windows have been deleted!"); /*$('#sBar').updateStatus("ok", "les fenêtres mémorisées ont été supprimées");*/
   			else alert("ERROR, the saved windows have not been deleted!");
   		},
		error: function() {
			alert("le serveur n’a pu être contacté, assurez-vous que vous êtes bien connecté(e) à internet");
		}
	});
}

function isAnyDuanzhu() {
	var myURL = "http://" + myHost + "/ajax/services.php";
	var myData = "data=isAnyDuanzhu&value=" + document.getElementById("thisPageID").value;

	// alert(myURL + "?" + myData);

	$.ajax({
		type: "GET",
		url: myURL,
		data: myData,
		success: function(HTML) {
   			if (HTML == "OK")
   			{
   				// alert("les fenêtres ont été mémorisées");
   				$('#isAnyDuanzhu').css('display', 'block');
   				$('#isAnyDuanzhu').css('visibility', 'visible');
   				
   			}
   			// else alert("les fenêtres n’ont pas été mémorisées !");
   		},
		error: function() {
			alert("le serveur n’a pu être contacté, assurez-vous que vous êtes bien connecté(e) à internet");
		}
	});

}

function catchComment(id) {
	var url = "http://" + myHost + "/ajax/comment.php";
	var data = "do=catch&id=" + id;

	$.ajax({
		type: "GET",
		url: url,
		data: data,
		success: function(html) {
   			// else alert("les fenêtres n’ont pas été mémorisées !");
   		},
		error: function() {
			// alert("le serveur n’a pu être contacté, assurez-vous que vous êtes bien connecté(e) à internet");
		}
	});
}


function exists(myUnicode)
{
	var myURL = "http://" + myHost + "/ajax/exists.php";
	var myData = "unicode=" + myUnicode;

	$.ajax({
		type: "GET",
		url: myURL,
		data: myData,
		success: function(HTML) {
   			if (HTML == "KO") alert(document.getElementById("notInShuowen").value);
   			else location.href = "?unicode=" + myUnicode;
   		},
		error: function() {
			alert("le serveur n’a pu être contacté, assurez-vous que vous êtes bien connecté(e) à internet");
		}
	});
}

function toOID(Event)
{
	if (Event == null)
	{
  		alert("une erreur s’est produite");
		Event = event;
  	}
	cod = Event.keyCode;
	switch (cod)
	{
		case 13:
			if (document.getElementById("OID").value != "") location.href = "?id=" + document.getElementById("OID").value;
		break;
	}
}

function toRecord(what)
{
	var order = document.getElementById("order").value;

	var myURL = "http://" + myHost + "/ajax/move.php";
	var myData = "id=" + document.getElementById("id").value + "&order=" + order + "&value=" + document.getElementById(order).value + "&to=" + what;

	$.ajax({
		type: "GET",
		url: myURL,
		data: myData,
		success: function(HTML) {
   			if (HTML == "KO") alert("aucun enregistrement ne correspond à votre requête");
   			else location.href = "?id=" + HTML;
   		},
		error: function() {
			alert("le serveur n’a pu être contacté, assurez-vous que vous êtes bien connecté(e) à internet");
		}
	});
}

function toOrder(order)
{
	document.getElementById("order").value = order;
	document.getElementById("orderForm").submit();
}

/* http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_str_replace */
function str_replace(search, replace, subject)
{
    var f = search, r = replace, s = subject;
    var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
 
    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    };
 
    return sa ? s : s[0];
}

function hex(hex)
{
	this.hex = hex;
	this.toDecimal = function() { return parseInt(this.hex, 16); }
	this.toBinary = function() { return this.toDecimal().toString(2); }
	this.toOctal = function() { return this.toDecimal().toString(8); }
}

function CNS(myCNS)
{
	var myCode = new Array();
    myCode = myCNS.split("-");
    myCode[1] = new hex(myCode[1]).toDecimal();
    myURL = "http://www.cns11643.gov.tw/web/show_font.jsp?page_n=" + myCode[0] + "&number=" + myCode[1];
    return myURL;
}

jQuery.fn.updateStatus = function(state, content) {
	switch (state) {
		case "ok":
			$(this).addClass("mBlueGood");
			break;

		case "error":
			$(this).addClass("mBlueBad");
			break;
	}
	
	$(this).html(content);
	$(this).highlightFade({ color:"#8DC0C9", speed:500, iterator:"linear", end:"#4F7E8F" });
};

