/**
 * X-Site Comments library draft
 * by Anatoly Matyakh <protopartorg@gmail.com>
 */
 
var xComInitTimer = 0;
var xComOptions = {
	jqueryurl:'http://xcom.service.net.ua/jquery.js',
	server:'http://xcom.service.net.ua/engine/xcom',
	loading:'<img src="http://xcom.service.net.ua/images/l.gif" hspace="16" vspace="16" border="0" width="32" height="32" alt="loading..." />',
	css:'http://xcom.service.net.ua/css/default.css',
	jquerycheck:true,
	place:'#xCom',
	create:false,
	append:'body',
	site:'',
	thread:'',
	flat:false
};
var xCom = false;	// Container call

/*
	Options Explained:
		
		jqueryurl: holds URL of jQuery JavaScript library
		jquerycheck: force check of jQuery presence
		place: 
			CSS-like selector for comments placeholder
			E.g. '#myId' for element with id="myId" or 'div.xCom' for DIV class="xcom"
			Only first element used if multiple elements found
		create: create placeholder
		append: where to append a created placeholder (CSS-like selector)
		site: canonized hostname or literal site id for xCom service
		thread: thread id (unique id of this page, can be a news-id, blog record id or even page URL)
		flat: display flat comments instead of threaded
*/

// xComInit();

function xComInit(opts){
	if(typeof opts == 'object'){
		if(opts.hasOwnProperty('place')) xComOptions.place = opts.place;
		if(opts.hasOwnProperty('create')) xComOptions.create = opts.create;
		if(opts.hasOwnProperty('append')) xComOptions.append = opts.append;
		if(opts.hasOwnProperty('site')) xComOptions.site = opts.site;
		if(opts.hasOwnProperty('thread')) xComOptions.thread = opts.thread;
		if(opts.hasOwnProperty('flat')) xComOptions.flat = opts.flat;
		if(opts.hasOwnProperty('css')) xComOptions.flat = opts.css;
		if(opts.hasOwnProperty('loading')) xComOptions.flat = opts.loading;
	}
	if(xComOptions.jquerycheck){
		if(typeof jQuery != 'function'){
			if(!xComInitTimer){
				xComCall(xComOptions.jqueryurl,'jqueryscript');
			}
			xComInitTimer++;
			if(xComInitTimer<50){
				setTimeout('xComInit(false)',100);
			}
			return false;
		}
	}
	
	jQuery(function(){
		if(xComOptions.create){
			xCom = $('<div />');
			xCom.appendTo(xComOptions.append);
		}else{
			var found = $(xComOptions.place);
			if(found){
				xCom = found.eq(0); // only first element
			}
		}
		
		if(xCom){
			if(xComOptions.site == ''){
				xComOptions.site = window.location.hostname;
			}
			if(xComOptions.thread == ''){
				xComOptions.thread = window.location.pathname + window.location.search;
			}
			
			if(xComOptions.css){
				$('head').append('<link rel="stylesheet" type="text/css" href="' + xComOptions.css + '" />');
	/*			var oLink = document.createElement("link");
				oLink.href = xComOptions.css; 
				oLink.rel = "stylesheet"; 
				oLink.type = "text/css"; 
				document.getElementsByTagName("head")[0].appendChild(oLink); */
			}
			
			xComLoadComments(false,false);
		}
	});
}

/* bookmarklet


javascript:var%20s=document.createElement('script');s.type='text/javascript';s.src='http://new.zmeuka.kiev.ua/xcom/xcom.js';document.getElementsByTagName("head")[0].appendChild(s);bminit();function%20bminit(){if(typeof%20xComInit!='function'){setTimeout('bminit()',100);}else{xComInit({create:true});}}


*/

function xComCall(url,placeholder){
	var oldScript = document.getElementById(placeholder);
	var headID = document.getElementsByTagName("head")[0];         
	if(oldScript) headID.removeChild(oldScript);
	var newScript = document.createElement('script');
	newScript.type = 'text/javascript';
	newScript.id = placeholder;
	newScript.src = url;
	headID.appendChild(newScript);
}

function xComSubmit(formid,callback){
	var $form = $('#'+formid);
	var form = $form[0];
	var id = 'FormIO' + (new Date().getTime());
	var $io = $('<iframe id="' + id + '" name="' + id + '" />');
	var io = $io[0];

	if ($.browser.msie || $.browser.opera) 
		io.src = 'javascript:false;document.write("");';
	$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

	var timedOut = 0;

	// take a breath so that pending repaints get some cpu time before the upload starts
	setTimeout(function() {
		// make sure form attrs are set
		var t = $form.attr('target');
		$form.attr({
			target:   id,
			encoding: "application/x-www-form-urlencoded",
			enctype:  "application/x-www-form-urlencoded",
			method:   'POST'
		});

		try {
			// add iframe to doc and submit the form
			$io.appendTo('body');
			io.attachEvent ? io.attachEvent('onload', cbhandler) : io.addEventListener('load', cbhandler, false);
			form.submit();
		}
		finally {
			// reset attrs and remove "extra" input elements
			t ? $form.attr('target', t) : $form.removeAttr('target');
		}
	}, 10);
	
	function cbhandler(){
		if(typeof callback == 'function')
			callback();
		// clean up
		setTimeout(function() {
			$io.remove();
		}, 100);
	}
	
	return false;
}

function xComCallBack(tag,content){
	switch(tag){
		case 'xcom-list':
			xCom.html(content);
			xCom.find('.highlighted').css('border','1px solid red').focus();
			break;
		case 'xcom-form':
			var newForm = $('#xcom-form-container');
			if(!newForm.size()){
				newForm = $('<div id="xcom-form-container" style="text-align:left"></div>');
			}
			newForm.html(content);
			var xId = newForm.find('#form-xcreply').val();
			if(xId && xId != '0'){	
				newForm.appendTo('#xcom-'+xId);
			}else{
				newForm.insertAfter('#xcom-top');
			}
			newForm.find('#form-xctext').focus();
			xComDogMeat();
			break;
		case 'xcom-dog':
			$('#form-xcdog').html(content);
			break;
		case 'xcom-retry':
			$('#xcom-form').before(content);
			xComDogMeat();
	}
}

/*
var xComOptions = {
	jqueryurl:'http://new.zmeuka.kiev.ua/xcom/jquery.js',
	server:'http://new.zmeuka.kiev.ua/xcom/xcom.cgi',
	jquerycheck:true,
	place:'#xCom',
	create:false,
	append:'body',
	site:'',
	thread:'',
	flat:false
};
*/


function xComLoadComments(page,stamp){
	var url = 
		xComOptions.server 
		+ '?site=' + encodeURIComponent(xComOptions.site)
		+ '&thread=' + encodeURIComponent(xComOptions.thread);
	if(page){
		url += '&page=' + encodeURIComponent(page);
	}
	url += '&style=';
	if(xComOptions.flat){
		url += 'flat';
	}else{
		url += 'threaded';
	}
	if(window.location.hash != ''){
		url += '&directid=' + encodeURIComponent(window.location.hash);
	}
	if(stamp){
		url += '&stamp=' + encodeURIComponent(stamp);
	}
	url += '&r=' + Math.random();
	xComCall(url,'xComCommentsScript');
}

function xComDogMeat(){
	$('#form-xcdog').html(xComOptions.loading);
	xComCall(xComOptions.server + '/dog?r=' + Math.random(),'xComCommentsScript');
	return false;
}

function xComLoadForm(id){
	var url = 
		xComOptions.server 
		+ '/addform'
		+ '?site=' + encodeURIComponent(xComOptions.site)
		+ '&thread=' + encodeURIComponent(xComOptions.thread)
		+ '&reply=' + encodeURIComponent(id);
	url += '&r=' + Math.random();
	xComCall(url,'xComCommentsScript');
	return false;
}

function xComSubmitForm(){
	$('#xcname').val(escape($('#xcname_raw').val()));
	$('#xcsubj').val(escape($('#xcsubj_raw').val()));
	$('#xctext').val(escape($('#xctext_raw').val()));
	$('#xctitle').val(escape($('title').text()));
	xComSubmit('xcom-form',function(){
		xComLoadComments(0,$('#form-xcstamp').val());
	});
	return false;
}