function scrollToBottom(selector) {
	var psconsole = $(selector);
	psconsole.scrollTop(psconsole[0].scrollHeight - psconsole.height());
}
function buildMenuExtActions() {
	initCufon();
	return true;
}
///
function iwishtobuy_calc_total(order_value, amount, minv) {
	var order_value = parseInt(order_value);
	$('#total_amount').html(order_price[order_value]['price']);
	$('#order_amount').val(order_price[order_value]['price']);
	$('#order_value').val(order_value);
	//discount line
	if (order_price[order_value]['cool_value'] > 0) {
		$('#discount_line_value').html(order_price[order_value]['cool_value']);
		$('#discount_line_percent').html(order_price[order_value]['cool_percent']);
		$('#discount_line').show();
	}
	else $('#discount_line').hide();
	//price of
	if (order_price[order_value]['price_off'] > 0) {
		$('#price_off').html(order_price[order_value]['price_off']);
		$('#wrapper_price_off').show();
	}
	else $('#wrapper_price_off').hide();
	
	//show hide discount line
	if (order_price[order_value]['cool_value']) $('#discount_line').show();
	else $('#discount_line').hide();

}
function onClickRateBtn(id) {

	//show submit btn
	$('#publish_rate_btn').show();
	
	//set all buttons unpress
	$('#fail_btn').css('background-position', '0 0');
	$('#success_btn').css('background-position', '0 0');	
	$('#none_btn').css('background-position', '0 0');
	
	//set all checkbox unchecked
	$('#fail_chb').attr('checked', false); 
	$('#success_chb').attr('checked', false); 
	$('#none_chb').attr('checked', false); 
	
	if (id == 'fail_btn') {
		text_color = 'red';
		chb_id = 'fail_chb';
	}
	else if (id == 'success_btn') {
		text_color = 'green';
		chb_id = 'success_chb';
	}
	else if (id == 'none_btn') {
		text_color = 'black';
		chb_id = 'none_chb';
	}
	
	//set checkbox
	$('#'+chb_id).attr('checked', true); 
	//set comment text color
	$('#public_comment').css('color', text_color);
	//set button to pressed view
	$('#'+id).css('background-position', '0 -30px'); 
	
	return true;
}
function aliasAvailable(value) {
	clearTimeout(window.timerAliasAvailable);
	xajax_aliasAvailable(value);
}
function startAliasAvailable(value, interval, discount, book) {
	$('#alias_available').html('');
	document.getElementById('affilaiteId').value = "http://"+discount+"/"+value+"/";
	document.getElementById('bookId').value = "http://"+book+"/"+value+"/";
	window.timerAliasAvailable = setTimeout('aliasAvailable("'+value+'")', interval);
}
function all_height_sum(cl1, cl2){
	sum1=0;
	$('.'+cl1).each(function(){
		sum1=sum1+$(this).height();
	});
	
	sum2=0;
	$('.'+cl2).each(function(){
		sum2=sum2+$(this).height();
	});
	if(sum1 > sum2){
		$('.'+cl2).last().height(($('.'+cl2).last().height()+sum1-sum2));
	}else if(sum1 < sum2){
		$('.'+cl1).last().height(($('.'+cl1).last().height()+sum2-sum1));
	}
}
function all_height(class_name){
	var max=0;
	$(class_name).each(function(){
		if(max < $(this).height())max=$(this).height();
	});
	$(class_name).height(max);
}

function shutdownTinyMCE(id_div) {
	$('#'+id_div).find('textarea').each(function(){
		var id_mce = $(this).attr('id');
		if (typeof(tinyMCE)!='undefined')
			if (id_mce && tinyMCE.get(id_mce) != 'undefined') tinymce.execCommand('mceRemoveControl', true, id_mce);
	});
}

function enableSwipeSelector(id_mce, id_selector) {
	if (tinyMCE.get(id_mce) == 'undefined') {
		//alert(1);
		return false;
	}
	else {
		//alert(id_selector);
		$('#'+id_selector).removeAttr('disabled');
		return true;
	}
}

function initCufon() {
	//Cufon.replace(".lvnm", {fontFamily: 'Levenim MT' });
	//Cufon.replace(".candara", {fontFamily: 'Candara' });
	//Cufon.replace(".leelawadee", {fontFamily: 'Leelawadee' });
}

function footer2bottom(class_name) {
	$("body").css({padding:0,margin:0});
	var f = function() {
		$("."+class_name).css({position:"relative"});
		var h1 = $("body").height();
		var h2 = $(window).height();
		var d = h2 - h1;
		var h = $("."+class_name).height() + d;    
		var ruler = $("<div>").appendTo("."+class_name);       
		h = Math.max(ruler.position().top,h);
		ruler.remove();    
		$("."+class_name).height(h);
	};
	setInterval(f,1000);
	//$(window).resize(f);
    f();	
}

function manualAddScript(src) {
	var head=document.getElementsByTagName('head')[0];
	script=document.createElement('script');
	script.type='text/javascript';
	script.src=src+'?' + Math.floor(Math.random()*99999);
	head.appendChild(script);
}

var tinyMCE_drop_position = 'absolute';
function initTinyMCE(extOpt) {
	//для устранения баги позиционирования дроп листов (шрифт, цвет и т.д.) необходимо иметь:
	//1) глобальную js перенную var tinyMCE_drop_position = 'absolute'; - юзается в исходнике исправленного tinyMCE_src.js
	//2) исправленную функцию winxajaxparse() - назначающая временно fixed для tinyMCE_drop_position, на момент открытого окна
	//3) исправленный js код tinyMCE. см. tiny_mce_src.js
	var baseOpt = {
		// General options
		//mode : inp_mode,
		//elements : inp_elements,
        theme : "advanced",
		//editor_selector : "mceEditor",
		plugins : "pagebreak,style,layer,table,save,advhr,advimage,emotions,iespell,insertdatetime,preview,media,searchreplace,print,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,inlinepopups",

		// Theme options
		theme_advanced_buttons1 : "bold,italic,underline,|,fontselect,fontsizeselect,forecolor,backcolor,|,link,numlist,|,justifyleft,justifycenter,justifyright,justifyfull",
        theme_advanced_buttons2 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_resizing : false,
		content_css : "http://www.safe-swaps.com/css/mce_custom_content.css",
		theme_advanced_font_sizes: "10px,12px,13px,14px,16px,18px,20px",
		font_size_style_values : "10px,12px,13px,14px,16px,18px,20px",
        theme_advanced_fonts : "Arial=arial,helvetica,sans-serif;"+
                "Courier New=courier new,courier;"+
                "Georgia=georgia,palatino;"+
                "Helvetica=helvetica;"+
                "Impact=impact,chicago;"+
                "Tahoma=tahoma,arial,helvetica,sans-serif;"+
                "Times New Roman=times new roman,times;"+
                "Verdana=verdana,geneva",

		relative_urls: false,
		remove_script_host: false,

        paste_preprocess : function(pl, o) {
			o.content = o.content.replace("<pre>", "");
			o.content = o.content.replace("</pre>", "");
        },
		
		template_replace_values : {
			username : "Some User",
			staffid : "991234"
		}
	};
	
	var opt = new Object();
	for (key in baseOpt) opt[key] = baseOpt[key];
	for (key in extOpt) opt[key] = extOpt[key];
	
	tinyMCE.init(opt);

	window.setTimeout("blockMCELinks()", 500);
}

// admin TinyMCE
function initTinyMCEAdmin(extOpt) {
	//для устранения баги позиционирования дроп листов (шрифт, цвет и т.д.) необходимо иметь:
	//1) глобальную js перенную var tinyMCE_drop_position = 'absolute'; - юзается в исходнике исправленного tinyMCE_src.js
	//2) исправленную функцию winxajaxparse() - назначающая временно fixed для tinyMCE_drop_position, на момент открытого окна
	//3) исправленный js код tinyMCE. см. tiny_mce_src.js
	var baseOpt = {
		// General options
		//mode : inp_mode,
		//elements : inp_elements,
        theme : "advanced",
		//editor_selector : "mceEditor",
		plugins : "pagebreak,style,layer,table,save,advhr,advimage,emotions,iespell,insertdatetime,preview,media,searchreplace,print,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,inlinepopups",

		// Theme options

		theme_advanced_buttons1 : "bold,italic,underline,|,fontselect,fontsizeselect,forecolor,backcolor,|,link,numlist,|,justifyleft,justifycenter,justifyright,justifyfull,|,image",
        theme_advanced_buttons2 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_resizing : false,
		content_css : "http://www.safe-swaps.com/css/mce_custom_content.css",
		theme_advanced_font_sizes: "10px,12px,13px,14px,16px,18px,20px",
		font_size_style_values : "10px,12px,13px,14px,16px,18px,20px",
        theme_advanced_fonts : "Arial=arial,helvetica,sans-serif;"+
                "Courier New=courier new,courier;"+
                "Georgia=georgia,palatino;"+
                "Helvetica=helvetica;"+
                "Impact=impact,chicago;"+
                "Tahoma=tahoma,arial,helvetica,sans-serif;"+
                "Times New Roman=times new roman,times;"+
                "Verdana=verdana,geneva",

		relative_urls: false,
		remove_script_host: false,
		file_browser_callback : "AjexFileManager.open",

        paste_preprocess : function(pl, o) {
			o.content = o.content.replace("<pre>", "");
			o.content = o.content.replace("</pre>", "");
        },

		template_replace_values : {
			username : "Some User",
			staffid : "991234"
		}
	};

	var opt = new Object();
	for (key in baseOpt) opt[key] = baseOpt[key];
	for (key in extOpt) opt[key] = extOpt[key];

	tinyMCE.init(opt);

	AjexFileManager.init({
		returnTo: 'tinymce'
	});
}

//only for FF
function blockMCELinks() {
	if (tinyMCE.activeEditor != null && tinyMCE.activeEditor.isHidden() == false) {
		var links = tinyMCE.activeEditor.getDoc().getElementsByTagName("a");
    	for (i = 0; i < links.length; i++) {
         	links[i].setAttribute("onclick", "return false");
    	}
	}
}

function processViewLinks(obj, action) {
	if (obj.value > 0) $('#'+obj.id+'_view').show();
	else $('#'+obj.id+'_view').hide();
	if (action == 'href') {
		$('#'+obj.id+'_view').attr('href', $('#'+obj.id+' option:selected').html());
	}
	else {
		$('#'+obj.id+'_view').attr('href', '/im_myads_preview.php?id='+$('#'+obj.id+' option:selected').attr('value'));
	}
}

function copytext(id) {
	if (el = document.getElementById(id)) {
		el.select(); 
		document.execCommand('Copy');
	}
}

function ctrlEnter(event) {
    if((event.ctrlKey) && ((event.keyCode == 0xA)||(event.keyCode == 0xD)))
        {
        return true;
        }
		else return false;
}


function fnShowProps(obj, objName){
   var result = "";
   for (var i in obj) // ��������� � ��������� ������� �� �������
       result += objName + "." + i + " = " + obj[i] + "<br />\n";
   alert(result);
}

function stripslashes( str ) {
   // *     example 1: stripslashes('Kevin\'s code');
   // *     returns 1: "Kevin's code"
   // *     example 2: stripslashes('Kevin\\\'s code');
   // *     returns 2: "Kevin\'s code"
   return (str+'').replace(/\0/g, '0').replace(/\\([\\'"])/g, '$1');
}
function str_replace(needle, replacement, haystack) {
	var temp = haystack.split(needle);
	return temp.join(replacement);
}

function preventSelection(element){
  var preventSelection = false;

  function addHandler(element, event, handler){
    if (element.attachEvent)
      element.attachEvent('on' + event, handler);
    else
      if (element.addEventListener)
        element.addEventListener(event, handler, false);
  }
  function removeSelection(){
    if (window.getSelection) { window.getSelection().removeAllRanges(); }
    else if (document.selection && document.selection.clear)
      document.selection.clear();
  }
  function killCtrlA(event){
    var event = event || window.event;
    var sender = event.target || event.srcElement;

    if (sender.tagName.match(/INPUT|TEXTAREA/i))
      return;

    var key = event.keyCode || event.which;
    if (event.ctrlKey && key == 'A'.charCodeAt(0))  // 'A'.charCodeAt(0) ����� �������� �� 65
    {
      removeSelection();

      if (event.preventDefault)
        event.preventDefault();
      else
        event.returnValue = false;
    }
  }

  // �� ���� �������� ����� ������
 /* 
  addHandler(element, 'mousemove', function(){
    if(preventSelection)
      removeSelection();
  });
  addHandler(element, 'mousedown', function(event){
    var event = event || window.event;
    var sender = event.target || event.srcElement;
    preventSelection = !sender.tagName.match(/INPUT|TEXTAREA/i);
  });
  */

  // ����� dblclick
  // ���� ������ ������� �� �� ������� dblclick, ����� ��������
  // ��������� ��������� ������ � ��������� ���������
  addHandler(element, 'mouseup', function(){
    if (preventSelection)
      removeSelection();
    preventSelection = false;
  });

  // ����� ctrl+A
  // ������ ����� ��� � �� ����, � ���� �� ���� ����������
  // ��� � ������ ��� �� ����� ������������� ������� �����
  // ������ ���� ��� � �� document, � �� �� �������
  addHandler(element, 'keydown', killCtrlA);
  addHandler(element, 'keyup', killCtrlA);
}


function showLoadingMessage() {
        var sizes = getWindowSizes();
        var scrolls = getScrollXY();
        var h =  xajax.$('loadingMessage').style.height.substring(0,
xajax.$('loadingMessage').style.height.length-2);
        var w =  xajax.$('loadingMessage').style.width.substring(0,
xajax.$('loadingMessage').style.width.length-2);
        var xTop = sizes[1]/2 + scrolls[1] - h;
        var xLeft = sizes[0]/2 + scrolls[0] - w/2;
        xajax.$('loadingMessage').style.top = xTop+'px';
        xajax.$('loadingMessage').style.left = xLeft+'px';
        xajax.$('loadingMessage').style.display='block';
}

function hideLoadingMessage() {
        xajax.$('loadingMessage').style.display = 'none';
}

function siteLoading() {
	document.getElementById('site_loading_progress_wrapper').style.display="none";
	document.getElementById('site_wrapper').style.visibility="visible";
}
///////////////////////////////////////////////////////////////
function setCenter2(id_layer) {
var scrollLeft, scrollTop;
if (window.pageYOffset) {
	scrollTop = window.pageYOffset
}
else if (document.documentElement && document.documentElement.scrollTop) {
	scrollTop = document.documentElement.scrollTop;
}
else if (document.body) {
	scrollTop = document.body.scrollTop;
}
if (window.pageXOffset) {
	scrollLeft=window.pageXOffset
}
else if (document.documentElement && document.documentElement.scrollLeft) {
	scrollLeft=document.documentElement.scrollLeft;
}
else if (document.body) {
	scrollLeft=document.body.scrollLeft;
}
var windowWidth, windowHeight;
if (window.innerWidth) {
	windowWidth=window.innerWidth;
}
else if (document.documentElement && document.documentElement.clientWidth) {
	windowWidth=document.documentElement.clientWidth;
}
else if (document.body) {
	windowWidth=document.body.offsetWidth;
}
if (window.innerHeight) {
	windowHeight=window.innerHeight;
}
else if (document.documentElement && document.documentElement.clientHeight){
	windowHeight=document.documentElement.clientHeight;
}
else if (document.body){
	windowHeight=document.body.clientHeight;
}
var layerWidth, layerHeight;
layerWidth=document.getElementById(id_layer).offsetWidth;
layerHeight=document.getElementById(id_layer).offsetHeight;

var delta;
delta = windowHeight - layerHeight;
if (delta < 0) delta=0;
document.getElementById(id_layer).style.top = (delta)/2 + scrollTop + 'px';
document.getElementById(id_layer).style.left = (windowWidth - layerWidth)/2 + 'px';
}
///////////////////////////////////////////////////////////////
function showWin(id) {
	if (document.getElementById(id)) document.getElementById(id).style.display = 'block';
}
///////////////////////////////////////////////////////////////
function hideWin(id) {
	if (document.getElementById(id)) document.getElementById(id).style.display = 'none';
}
///////////////////////////////////////////////////////////////
function checkAll(oForm, cbName, checked) {
	for (var i=0; i < oForm[cbName].length; i++) oForm[cbName][i].checked = checked;
}
////////////////////////////////////////////////////////////////
function askConfirm(text, func_name) {
	if (confirm(text)) {
		eval(func_name);
		return false;
	}
	else return false;
}
///////////////////////////////////////////////////////////////
function setCenter(divID, w, h)
{

	if (div = document.getElementById(divID)) {
		var sizes = getWindowSizes();
		var scrolls = getScrollXY();
		if (!h) h = div.style.height.substring(0,  div.style.height.length-2);
		if (!w) w = div.style.width.substring(0,  div.style.width.length-2);
		//if (!h) h = document.getElementById('popup_sub').offsetHeight;
		//if (!w) w = document.getElementById('popup_sub').offsetWidth;
		var xTop = sizes[1]/2 + scrolls[1] - h/2;
		var xLeft = sizes[0]/2 + scrolls[0] - w/2;
		div.style.top = xTop+'px';
		div.style.left = xLeft+'px';
	}
}
///////////////////////////////////////////////////////////////
function getScrollXY() {
   var scrOfX = 0, scrOfY = 0;
   if( typeof( window.pageYOffset ) == 'number' ) {
     //Netscape compliant
     scrOfY = window.pageYOffset;
     scrOfX = window.pageXOffset;
   } else if( document.body && ( document.body.scrollLeft ||
document.body.scrollTop ) ) {
     //DOM compliant
     scrOfY = document.body.scrollTop;
     scrOfX = document.body.scrollLeft;
   } else if( document.documentElement &&
( document.documentElement.scrollLeft ||
document.documentElement.scrollTop ) ) {
     //IE6 standards compliant mode
     scrOfY = document.documentElement.scrollTop;
     scrOfX = document.documentElement.scrollLeft;
   }
   return [ scrOfX, scrOfY ];
}
///////////////////////////////////////////////////////////////
function getWindowSizes() {
   var myWidth = 0, myHeight = 0;
   if( typeof( window.innerWidth ) == 'number' ) {
     //Non-IE
     myWidth = window.innerWidth;
     myHeight = window.innerHeight;
   } else if( document.documentElement &&
( document.documentElement.clientWidth ||
document.documentElement.clientHeight ) ) {
     //IE 6+ in 'standards compliant mode'
     myWidth = document.documentElement.clientWidth;
     myHeight = document.documentElement.clientHeight;
   } else if( document.body && ( document.body.clientWidth ||
document.body.clientHeight ) ) {
     //IE 4 compatible
     myWidth = document.body.clientWidth;
     myHeight = document.body.clientHeight;
   }
   return [ myWidth, myHeight ];
}
///////////////////////////////////////////////////////////////

function closeWindow(id_layer) {
	document.getElementById(id_layer).style.visibility = "hidden";
}
