/*
Hierarchic comments. JavaScript implementation part.
Property: bigmir)net
Author: Alexey Karpinskiy (alex_kiy@bigmir.net)
Release date: november 2007
*/
// Global structure with settings. Included in source code to preserve compatibility and save js module integrity
// May be redeclared in comment's html source.
// Can be cutted off here and simply placed in source html output in script tags
if(typeof(window.commJsGlVar) == 'undefined') {
window.commJsGlVar = {
bmImgServer : 'http://i.bigmir.net/',
commCaptchaWebPath : 'http://main.bigmir.net/include/c_captcha.inc.php',
commScriptFullUrl : window.location.protocol + '//' + window.location.host + window.location.pathname + '/',
commTplIdPrefix : 'CMNT_ID_',
commTplAnchorPrefix : 'CMNT_ANCHOR_',
commNullId : 0,
commID : 0,
commErrorMsg : false
};
}
// --------------- Ajax loader ------
function commHttpLoad(vars) {
if (vars) vars[vars.length] = {'name':'ajaxify', 'value':'1'};
var cObj = new UserHttpRequest(vars, commJsGlVar.commScriptFullUrl);
cObj.curSpecificAction = false;
for(var i = 0; i < vars.length; i++) {
switch(vars[i].name) {
case 'addcomment' : {
cObj.curSpecificAction = true;
break;
}
case 'sort': {
if(typeof(commSortOrder)!="undefined")
commSortOrder = vars[i].value;
break;
}
}
if(cObj.curSpecificAction === true) break;
}
cObj.onSate_Complete = function() {
if(cObj.httpRequest.responseJS.body) {
var comLayer = $('#comment_header_layer');
if(comLayer && cObj.httpRequest.responseJS.body) {
comLayer.html($.trim(cObj.httpRequest.responseJS.body));
commJsGlVar.commErrorMsg = Boolean(cObj.httpRequest.responseJS.errorMsg);
commJsGlVar.commID = parseInt(cObj.httpRequest.responseJS.ID);
initComments(Boolean(!this.curSpecificAction));
}
}
}
cObj.Do_BeforSend = function() {
Change_LayerVisibility('imgLoaderStatus_1', true, false);
Change_LayerVisibility('imgLoaderStatus_2', true, false);
}
cObj.Do_After_ExceedTimeout = function() {
Change_LayerVisibility('imgLoaderStatus_1', false, true);
Change_LayerVisibility('imgLoaderStatus_2', false, true);
}
cObj.Load(true);
return false;
}
function commHttpLoadContainer(obj, i) {
vars = [{name:'p', value:i}, {name:'sort', value:commSortOrder}];
return commHttpLoad(vars);
}
// captcha reloader
function reloadCommCaptcha() {
/*
captcha_IMG = Get_DOM_Node('captcha_img');
captcha_IMG.src = commJsGlVar.commCaptchaWebPath + '?' + Math.random();
*/
var capObj = new UserHttpRequest([{'rand':'', 'value':Math.random()}], commJsGlVar.commCaptchaWebPath);
capObj.onSate_Complete = function() {
var captcha_cont = $('#captcha_container');
if(captcha_cont && capObj.httpRequest.responseJS.body) {
captcha_cont.html(capObj.httpRequest.responseJS.body);
}
}
capObj.Load(true);
return false; // should return false
}
// text symbol counter
function limitInputText(input, maxlen, left) {
input = $(input);
inputstr = input.val();
strlen = inputstr.length;
if (strlen > maxlen) {
input.attr('value', inputstr.substring(0, maxlen));
}
if (left = $('#'+left)) {
if (left.attr('tagName') == 'INPUT') {
left.attr(value, maxlen - input.val().length);
}
else {
left.html(maxlen - input.val().length);
}
}
return true;
}
// clear/update name-field
function clearUNameBoxInput(obj, clear, text) {
if (clear && (obj.value == text)) obj.value='';
else if (obj.value == '') obj.value = text;
}
// form checker
function checkComForm() {
var cmnt_text = $('#cmnt_text');
if (cmnt_text && cmnt_text.val()=='') {
alert('Введите комментарий'); return false;
}
var captcha_msg = $('#msg_captcha');
if (captcha_msg && captcha_msg.val()=='') {
alert('Введите проверочный код'); return false;
}
return true;
}
// form data collector
function proceedComSubmit() {
if (typeof globalReCaptchaResponse != 'undefined' && globalReCaptchaResponse == '') {
gaCaptchaInit();
$('.g-recaptcha').show();
$('._submit_btn').hide();
return false;
}
$('._submit_btn').hide();
var form_Obj = $('#commAddForm');
if (form_Obj && checkComForm()) {
var serverParams = new Array(
{name:'addcomment', value:'true'},
{name:'cmnt_text', value: encodeURIComponent($.trim(form_Obj.find('#cmnt_text').val()))}, // send cyrilic text via JsHttpTransport
{name:'ID', value: form_Obj.find("input[name='ID']").val()}
);
if(form_Obj.find('._userName').length > 0) {
serverParams[serverParams.length] = {name:'userName', value: encodeURIComponent($.trim(form_Obj.find('._userName').val()))};
}
if (typeof globalReCaptchaResponse == 'undefined') {
if (form_Obj.find('#recaptcha_response_field')) {
serverParams[serverParams.length] = {
name: 'recaptcha_response_field',
value: $.trim(form_Obj.find('#recaptcha_response_field').val())
};
}
if (form_Obj.find('#recaptcha_challenge_field')) {
serverParams[serverParams.length] = {
name: 'recaptcha_challenge_field',
value: $.trim(form_Obj.find('#recaptcha_challenge_field').val())
};
}
} else {
if(globalReCaptchaResponse!='') {
serverParams[serverParams.length] = {name:'reCaptchaResponse', value: globalReCaptchaResponse};
}
}
if(form_Obj.find('#newComments')) {
var newCommentsRequest = form_Obj.find('#newComments').attr('checked') ? 1 : 0;
serverParams[serverParams.length] = {name:'newComments', value: newCommentsRequest};
}
if (form_Obj.attr('id') != 0) {
if(form_Obj.find('#displayModeCurrent')) {
serverParams[serverParams.length] = {name:'display', value:form_Obj.find('#displayModeCurrent').val()};
}
if(form_Obj.find('#currentPage')) {
serverParams[serverParams.length] = {name:'p', value: form_Obj.find('#currentPage').val()};
}
if(form_Obj.find('#sortMode')) {
serverParams[serverParams.length] = {name:'sort', value: form_Obj.find('#sortMode').val()};
}
}
var date = new Date();
var minutes = 10;
date.setTime(date.getTime() + (minutes * 60 * 1000));
$.cookie('user_nc', 'Y', {expires: date, path: location.pathname});
return commHttpLoad(serverParams);
}
$('._submit_btn').show();
return false;
}
// move scroll to given object
function adjustScrollPosition(comLayer) {
if (typeof(comLayer) == 'string') {
comLayer = $('#' +comLayer);
//comLayer = document.getElementById(comLayer);
}
if(comLayer && typeof(comLayer) == 'object') {
var coordX = f_scrollLeft();
var coordY = Find_AbsoluteDocObjCoord_Y(comLayer);
if(coordY > 0) scrollTo(coordX, coordY);
}
}
function f_scrollLeft() {
return f_filterResults (
window.pageXOffset ? window.pageXOffset : 0,
document.documentElement ? document.documentElement.scrollLeft : 0,
document.body ? document.body.scrollLeft : 0
);
}
function f_scrollTop() {
return f_filterResults (
window.pageYOffset ? window.pageYOffset : 0,
document.documentElement ? document.documentElement.scrollTop : 0,
document.body ? document.body.scrollTop : 0
);
}
function f_filterResults(n_win, n_docel, n_body) {
var n_result = n_win ? n_win : 0;
if (n_docel && (!n_result || (n_result > n_docel)))
n_result = n_docel;
return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}
// coment form container and modifier class
function hierarchicComment(){
this.node = null,
this.containerID = null, // contains comment's ID with opened form. Otherwise = null.
this.getFormNode= function() {
if(this.node != null) {// && this.node.nodeType > 0
var form = $('form', this.node).first();
//this.node.getElementsByTagName('FORM')[0];
return form;
}
else {
return null;
}
},
this.modifyCommFormNode = function(ID) {
var form = this.getFormNode();
if(form) {
// fix for safari. do not use "for(x in array)" syntax
/*if(typeof(form.ID) == 'undefined') {
for(var i=0; i
'
+ action + ' '
+ ''
+ ''+
*/
''
+ global_comment_settings_text2 + ' ');
}
if(direction == 'down') {
$('#CMNT_ID_0').show();
changeLayerVisibility(commJsGlVar.commNullId);
Change_LayerVisibility('com_header_bottom_corners', false, true);
Change_LayerVisibility('com_form_top_corners', false, true);
}
else if(direction == 'up') { // close comment form only if it opened in null comment place (top)
$('#CMNT_ID_0').hide();
var hJsHierarchComObj = initGetCommFormContainerObj();
var nullLayerObj = $('#' + commJsGlVar.commTplIdPrefix + commJsGlVar.commNullId);
if(nullLayerObj && typeof(hJsHierarchComObj) == 'object' && hJsHierarchComObj.containerID === commJsGlVar.commNullId) {
changeLayerVisibility(commJsGlVar.commNullId);
}
Change_LayerVisibility('com_header_bottom_corners', true, false);
Change_LayerVisibility('com_form_top_corners', true, false);
}
return false;
}
/* comment page initialization */
function initComments(forceScrollAdjust) {
$('#imgLoaderStatus_1').hide();
$('#imgLoaderStatus_2').hide();
attachJsActions();
initGetCommFormContainerObj(true);
changeAddHideText('down');
/*if(commJsGlVar.commErrorMsg) {
(commJsGlVar.commID == commJsGlVar.commNullId) ? changeAddHideText('down') : changeLayerVisibility(commJsGlVar.commID);
}
else {
changeAddHideText('down');
}*/
if(forceScrollAdjust === true || commJsGlVar.commErrorMsg) {
adjustScrollPosition(commJsGlVar.commTplAnchorPrefix + commJsGlVar.commID);
}
return false;
}
// creates an "hierarchicComment"-object and init it if necessary
// returns created comm-container object
function initGetCommFormContainerObj(forceInit) {
if(typeof(window.jsHierarchComObj) == 'undefined') {
window.jsHierarchComObj = new hierarchicComment();
forceInit = true;
}
if(forceInit) {
var nullFormContainer = $('#'+commJsGlVar.commTplIdPrefix + commJsGlVar.commNullId);
if(nullFormContainer) {
window.jsHierarchComObj.node = nullFormContainer.children().first(); nullFormContainer.empty();//DOM.cutNodeFirstChild(nullFormContainer);
window.jsHierarchComObj.containerID = null;
}
}
return window.jsHierarchComObj;
}
/*
main form visibility operator
*/
function changeLayerVisibility(commID) {
var xLayerObj = $('#'+commJsGlVar.commTplIdPrefix + commID);
var hJsHierarchComObj = initGetCommFormContainerObj();
if(xLayerObj && typeof(hJsHierarchComObj) == 'object') {
// close comment form in source place
if (hJsHierarchComObj.containerID == commID) {
if(xLayerObj.children()) {
hJsHierarchComObj.node = xLayerObj.children().first();
hJsHierarchComObj.containerID = null;
hideAllCommForms();
}
} else { // insert comment form into given comment ID thread
if(hJsHierarchComObj.containerID !== null) { // form is opened. close it first
var xPrevLayerObj = $('#'+commJsGlVar.commTplIdPrefix + hJsHierarchComObj.containerID);
if(xPrevLayerObj) {
hJsHierarchComObj.node = xPrevLayerObj.children().first(); xPrevLayerObj.empty();
hJsHierarchComObj.containerID = null;
}
}
//DOM.appendNode(xLayerObj, hJsHierarchComObj.modifyCommFormNode(commID));
xLayerObj.append(hJsHierarchComObj.modifyCommFormNode(commID));
hJsHierarchComObj.containerID = commID;
}
// close null comment form and change link text
if (commID != commJsGlVar.commNullId) {
changeAddHideText('up');
}
}
return false;
}
function answerCom(answerID){
hideAllCommForms();
$('#'+'answ_'+answerID).toggle();
/*
if(document.getElementById('answ_'+answerID)){
var oldStyle = document.getElementById('answ_'+answerID).style.display;
newStyle = oldStyle=='block'? "none" : "block";
hideAllCommForms();
document.getElementById('answ_'+answerID).style.display=newStyle;
}
*/
}
/* hide all comments form */
function hideAllCommForms(){
$('#comment_header_layer .insideform').hide();
/*
var clasObj = getElementsByClassName('comment_header_layer' ,'insideform');
for(i=0; i< clasObj.length; i++){
clasObj[i].style.display="none";
}
*/
}
function comment_addsmile(smile)
{
try
{
var cmnt_text = $('#cmnt_text');
cmnt_text.attr('value', cmnt_text.val() + smile);
cmnt_text.focus();
}catch (e){;}
}
function Change_LayerVisibility(id, forceOpen, forceClose) {
if (forceOpen) $('#'+id).show();
if (forceClose) $('#'+id).hide();
}
/*
Class UserHttpRequest
Makes AJAX Http Request and calls defined callback
@param:
qUrlPath = full path to server script
vars = [{'name':'GET_var_name', 'value:'GET_var_value'}, {'name':'GET_var_name', 'value:'GET_var_value'}, ...]
*/
function UserHttpRequest (vars, qUrlPath) {
var loadAttemptsTotal = 3;
this.httpRequest = new JSHttpRequest();
this.qTimeout = 0;
this.maxTimeout = 15*1000; // 15 sec
this.qUrlPath = qUrlPath;
this.q = new Object();
this.vars = (vars) ? vars : new Array();
this.autoReload = false; // repeat load after timeout exceeding
this.loadAttempt = loadAttemptsTotal;
var this_closure = this; // enclose object's properties and method in local variable
/*
Clear Callback Methods
Overload them in a caller function to process proper JS Http Callback
Important: run method Clear_Timeout() if data is loaded successfull to prevent Exceed Timeout procedure execution
*/
this.onState_Uninitialized = function() {}
this.onState_Loading = function() {}
this.onState_Loaded = function() {}
this.onSate_Interactive = function() {} // just notified english syntax error :)
this.onState_Interactive = function() {}
this.onSate_Complete = function() {} // just notified english syntax error :)
this.onState_Complete = function() {}
this.onState_Complete_globalCallback =
(typeof(window.UserHttpRequest_globalCallback) == 'function') ? window.UserHttpRequest_globalCallback : function() {}
this.httpRequest.onreadystatechange = function() {
switch(this_closure.httpRequest.readyState) {
case 0: this_closure.onState_Uninitialized(); break;
case 1: this_closure.onState_Loading(); break;
case 2: this_closure.onState_Loaded(); break;
case 3: {
this_closure.onSate_Interactive();
this_closure.onState_Interactive();
break;
}
case 4: {
this_closure.onSate_Complete();
this_closure.onState_Complete();
this_closure.onState_Complete_globalCallback();
break;
}
default: break;
}
this_closure.Clear_Timeout();
}
this.Update_Properties = function(vars, qUrlPath) {
this.q = (delete this.q, new Object());
this.vars = (vars) ? vars : new Array();
this.qUrlPath = (qUrlPath) ? qUrlPath : this.qUrlPath;
this_closure = this;
}
this.Prepare = function() {
this.q.dummy = Math.random();
this.q.DEBUG_MODE = 0;
if (typeof(comment_additional_get_param) != 'undefined') {
this.q[comment_additional_get_param] = comment_additional_get_param;
}
for (var i=0; i < this.vars.length; i++) {
this.q[this.vars[i].name] = this.vars[i].value;
}
}
this.Load = function(autoReload) {
this.autoReload = autoReload; //see vars declaration
this.Prepare();
this.Set_Timeout();
this.Do_BeforSend();
// send http request
this.httpRequest.caching = false; // caching is "false" by defaults
this.httpRequest.open('GET', this.qUrlPath, true);
this.httpRequest.send(this.q);
}
this.Set_Timeout = function() {
this.Clear_Timeout();
this.qTimeout = setTimeout(this.Exceed_Timeout, this.maxTimeout);
}
this.Clear_Timeout = function() {
if (this.qTimeout) clearTimeout(this.qTimeout);
}
this.Exceed_Timeout = function() {
this_closure.httpRequest.abort();
this_closure.Do_After_ExceedTimeout();
this_closure.Clear_Timeout();
if (this_closure.autoReload === true) {
if (this_closure.loadAttempt > 0) {
this_closure.loadAttempt--;
this_closure.Load(this_closure.autoReload);
}
else {
this_closure.loadAttempt = loadAttemptsTotal;
}
}
}
//Overload this methods to assign proper variant actions after exceeding loading timeout limit
this.Do_After_ExceedTimeout = function() {}
this.Do_BeforSend = function() {}
}
//JSHttpRequest v1.12. (C) Dmitry Koterov, 2005-01-27.
//http://forum.dklab.ru/users/DmitryKoterov/
function JSHttpRequest() {}
(function() {
var count = 0;
var pending = {};
var cache = {};
var spanReuse = null;
var getDiv =
document.all ?
function(sId) {return document.all[sId]}
:(document.getElementById ?
function(sId){return document.getElementById(sId)}
:function(sId){return null});
JSHttpRequest.dataReady = function(id, text, js, info) {
var undef;
var th = pending[id];
if (th) {
if (th.caching) cache[th.hash] = [text, js];
th._dataReady(text, js, info);
} else if (typeof(th) != typeof(undef)) {
alert("ScriptLoader: unknown pending id: "+id);
}
}
JSHttpRequest.prototype = {
onreadystatechange: null,
readyState: 0,
responseText: null,
responseXML: null,
status: 200,
statusText: "OK",
responseJS: null,
caching: false,
SID: null,
_span: null,
_id: null,
abort: function() { with (this) {
readyState = 0;
if (onreadystatechange) onreadystatechange();
_cleanupScript();
delete pending[_id];
}},
open: function(method, url, asyncFlag, username, password) {
if ((""+method).toLowerCase() != 'get') {
alert('Only GET method is supported!');
return false;
}
this.url = url;
return true;
},
send: function(content) {
var id = count;//++;
var query = [];
if (content instanceof Object) {
for (var k in content) {
query[query.length] = escape(k) + "=" + escape(content[k]);
}
} else {
query = [content];
}
var qs = query.join('&');
query = id + ':' + (this.SID || '') + ':' + qs;
var href = this.url + (this.url.indexOf('?')>=0? '&' : '?') + query;
var hash = this.url + '?' + qs;
this.hash = hash;
if (this.caching && cache[hash]) {
var c = cache[hash];
this._dataReady(c[0], c[1], c[1]);
return false;
}
this._obtainScript(id, href);
return true;
},
getAllResponseHeaders: function() {
return '';
},
getResponseHeader: function(label) {
return '';
},
setRequestHeader: function(label, value) {
},
_dataReady: function(text, js, info) { with (this) {
if (text !== null || js !== null) {
readyState = 4;
responseText = responseXML = text;
responseJS = js;
if ((typeof(info) == 'string') && info) {
var newDiv = $('newDiv');
if (!newDiv){
newDiv = $('');
newDiv.html(info);
$('body').append(newDiv);
}
}
} else {
readyState = 0;
responseText = responseXML = responseJS = null;
}
if (onreadystatechange) onreadystatechange();
_cleanupScript();
}},
_obtainScript: function(id, href) { with (document) {
var span = null;
if (spanReuse == null || !spanReuse.length) {
span = body.appendChild(createElement("SPAN"));
span.style.display = 'block';
//span.innerHTML = 'Text for stupid IE.' + 'script>';
span.innerHTML = 'Text for stupid IE';
} else {
span = spanReuse[spanReuse.length-1];
spanReuse[spanReuse.length-1] = null;
spanReuse.length--;
}
pending[id] = this;
setTimeout(function() {
//var s = span.getElementsByTagName("script")[0];
var s = span.appendChild(createElement("script"));
s.language = "JavaScript";
if (s.setAttribute) s.setAttribute('src', href); else s.src = href;
}, 100);
this._id = id;
this._span = span;
}},
_cleanupScript: function() {
var span = this._span;
if (span) {
this._span = null;
setTimeout(function() {
if (spanReuse != null) {
spanReuse[spanReuse.length] = span;
} else {
span.parentNode.removeChild(span);
}
}, 50);
}
return false;
}
}
})();
function Find_AbsoluteDocObjCoords(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft;
curtop = obj.offsetTop;
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
}
}
return [curleft, curtop];
}
function Find_AbsoluteDocObjCoord_X(obj) {
var coords = Find_AbsoluteDocObjCoords(obj);
return coords[0];
}
function Find_AbsoluteDocObjCoord_Y(obj) {
var coords = Find_AbsoluteDocObjCoords(obj);
return coords[1];
}