var Planetoid = new Object();

Planetoid.debug = function(ex) {
	$('#console').append(ex);
}

Planetoid.count = function(Obj) {
	var i=0;
	for (x in Obj) i++;
	return i;
}

//прячет элемент, если кликнуто вне его
Planetoid.hideOnClickOut = function(elem) {
	hideElem = function() {
		elem.hide();
		$(document).unbind('click',hideElem);
	}
	elem.mouseout(function(){
		$(document).bind('click',hideElem);
	}).mouseover(function(){
		$(document).unbind('click',hideElem);
	});
}

Planetoid.getClientWidth = function() {
	
	var x = 0;
	
	if (self.innerWidth) {
		x = self.innerWidth;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		x = document.documentElement.clientWidth;
	} else if (document.body) {
		x = document.body.clientWidth;
	}
	
	return x;
}

//Показывает предупреждение о переходе на чужой сайт
Planetoid.foreignLink = function (url,elem) {
	$(elem).parent().children('.foreign_link_warning').remove();
	
	$(elem).after('<div style="position:absolute;background:#fff;border:#993333 1px solid;padding:2px;z-index:2;//margin-top:15px;left:0" class="foreign_link_warning">Эта ссылка ведёт на другой сайт. Вы уверены, что хотите перейти по ней? <a href="'+url+'" target="_blank" onclick="Planetoid.foreignLinkHide(this)" style="text-decoration:none;border-bottom:1px dotted #3C6387;">Перейти</a> | <a href="javascript://" style="text-decoration:none;border-bottom:1px dotted #3C6387;" onclick="Planetoid.foreignLinkHide(this)">Отмена</a></div>');
}
//Прячет предупреждение о переходе на чужой сайт
Planetoid.foreignLinkHide = function(elem) {
	$(elem).parent().hide();
}

//Button handler
Planetoid.Btn = new Object();

//array of disabled btns
Planetoid.Btn.Disabled = new Array();

Planetoid.Btn.setLoading = function(btnId) {
	$('#'+btnId+'_loader').css('visibility','visible');
	$('#'+btnId).css('opacity','0.5');
	Planetoid.Btn.Disabled[btnId]=true;
}
Planetoid.Btn.unsetLoading = function(btnId) {
	$('#'+btnId+'_loader').css('visibility','hidden');
	$('#'+btnId).css('opacity','1');
	Planetoid.Btn.Disabled[btnId]=false;
}


//Получает значение куки с именем c_name
function getCookie(c_name) {
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
	  	if (c_start!=-1) { 
	    	c_start=c_start + c_name.length+1; 
	    	c_end=document.cookie.indexOf(";",c_start);
	    	if (c_end==-1) c_end=document.cookie.length;
	    	return unescape(document.cookie.substring(c_start,c_end));
	    } 
	  }
	return "";
}

//Возвращает инфу о браузере
function browserType(){
	if($.browser.msie) {
  		if (jQuery.browser.version.substr(0,1)=="6") return 'ie6';
  		else if (jQuery.browser.version.substr(0,1)=="7") return 'ie7';
  	}
	else if ($.browser.opera) {
		return 'opera';
	}
	else return false;
};

//Выводит методы обджекта
function viewObj(object) {
	var result = '';
	for (var property in object) {
		result += property + ': ' + object[property] + '\r\n';
	}
	return result;
}

//Аналог php in_array

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


//Аналог php trim

function trim(string) {
	return string.replace(/(^\s+)|(\s+$)/g, "");
}



//аналог php htmlspecialchars для динамического обновления вводимой пользователем информации
function htmlspecialchars(html) {
		try{
		// Сначала необходимо заменить &
      html = html.replace(/&/g, "&amp;");
      // А затем всё остальное в любой последовательности
      html = html.replace(/</g, "&lt;");
      html = html.replace(/>/g, "&gt;");
      html = html.replace(/"/g, "&quot;");
      // Возвращаем полученное значение
      return html;
		}catch(e){}
}

function nl2br (str) {
	return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br />$2');
}

//аналог php addslashes
function addslashes(str) {
    return str.replace('/(["\'\])/g', "\\$1").replace('/\0/g', "\\0");
}

//////////////////// scroll ////////////////////////////////////////////////////////////////////////////
jQuery.getPos = function (e)
{
	var l = 0;
	var t  = -20;
	var w = jQuery.intval(jQuery.css(e,'width'));
	var h = jQuery.intval(jQuery.css(e,'height'));
	var wb = e.offsetWidth;
	var hb = e.offsetHeight;
	while (e.offsetParent){
		l += e.offsetLeft + (e.currentStyle?jQuery.intval(e.currentStyle.borderLeftWidth):0);
		t += e.offsetTop  + (e.currentStyle?jQuery.intval(e.currentStyle.borderTopWidth):0);
		e = e.offsetParent;
	}
	l += e.offsetLeft + (e.currentStyle?jQuery.intval(e.currentStyle.borderLeftWidth):0);
	t  += e.offsetTop  + (e.currentStyle?jQuery.intval(e.currentStyle.borderTopWidth):0);
	return {x:l, y:t, w:w, h:h, wb:wb, hb:hb};
};
jQuery.getClient = function(e)
{
	if (e) {
		w = e.clientWidth;
		h = e.clientHeight;
	} else {
		w = (window.innerWidth) ? window.innerWidth : (document.documentElement && document.documentElement.clientWidth) ? document.documentElement.clientWidth : document.body.offsetWidth;
		h = (window.innerHeight) ? window.innerHeight : (document.documentElement && document.documentElement.clientHeight) ? document.documentElement.clientHeight : document.body.offsetHeight;
	}
	return {w:w,h:h};
};
jQuery.getScroll = function (e) 
{
	if (e) {
		t = e.scrollTop;
		l = e.scrollLeft;
		w = e.scrollWidth;
		h = e.scrollHeight;
	} else  {
		if (document.documentElement && document.documentElement.scrollTop) {
			t = document.documentElement.scrollTop;
			l = document.documentElement.scrollLeft;
			w = document.documentElement.scrollWidth;
			h = document.documentElement.scrollHeight;
		} else if (document.body) {
			t = document.body.scrollTop;
			l = document.body.scrollLeft;
			w = document.body.scrollWidth;
			h = document.body.scrollHeight;
		}
	}
	return { t: t, l: l, w: w, h: h };
};

jQuery.intval = function (v)
{
	v = parseInt(v);
	return isNaN(v) ? 0 : v;
};

jQuery.fn.ScrollTo = function(s) {
	o = jQuery.speed(s);
	return this.each(function(){
		new jQuery.fx.ScrollTo(this, o);
	});
};

jQuery.fx.ScrollTo = function (e, o)
{
	var z = this;
	z.o = o;
	z.e = e;
	z.p = jQuery.getPos(e);
	z.s = jQuery.getScroll();
	z.clear = function(){clearInterval(z.timer);z.timer=null};
	z.t=(new Date).getTime();
	z.step = function(){
		var t = (new Date).getTime();
		var p = (t - z.t) / z.o.duration;
		if (t >= z.o.duration+z.t) {
			z.clear();
			setTimeout(function(){z.scroll(z.p.y, z.p.x)},13);
		} else {
			st = ((-Math.cos(p*Math.PI)/2) + 0.5) * (z.p.y-z.s.t) + z.s.t;
			sl = ((-Math.cos(p*Math.PI)/2) + 0.5) * (z.p.x-z.s.l) + z.s.l;
			z.scroll(st, sl);
		}
	};
	z.scroll = function (t, l){window.scrollTo(l, t)};
	z.timer=setInterval(function(){z.step();},13);
};


//Отображает ссылку на админку, в случае если юзер - эйджент
function showAdminInfo(sessid) {
	$.ajax({
	type: "POST",
	url: gl_addr + 'showAdminInfo.php',
	data: postData,
	success: function(retHTML){
		if (retHTML=='OK') {
			$('adminLink').html('<strong><a rel="history" href="{$gl_addr}#admin/">Админка</a></strong>');
		}
	},
	error: function(retHTML){
	
	},
	datatype: "html"
	});
}

//Выделяет вкладку $tab
function selectTab(tab) {
	
	$('#tabs_panel ul li.selected').removeClass('selected');
	tab.addClass('selected');
	
	var leftClass = '';
	if (!tab.prev('li').prev('li').get(0)) {
		leftClass = 'sep_sel_l0'; 
	} else leftClass = 'sep_sel_l1';
	
	var rightClass = '';
	if (!tab.next('li').next('li').get(0)) {
		rightClass = 'sep_sel_r0'; 
	} else rightClass = 'sep_sel_r1';
	
	$('.separ').each(function(){
		if ($(this).hasClass('sep_sel_l1')) $(this).removeClass('sep_sel_l1').addClass('sep_r1');
		if ($(this).hasClass('sep_sel_l0')) $(this).removeClass('sep_sel_l0').addClass('sep_l0');
		if ($(this).hasClass('sep_sel_r1')) $(this).removeClass('sep_sel_r1').addClass('sep_r1');
		if ($(this).hasClass('sep_sel_r0')) $(this).removeClass('sep_sel_r0').addClass('sep_r0');
	});
	
	tab.prev('li').attr('class','separ '+leftClass+' png');
	tab.next('li').attr('class','separ '+rightClass+' png');
	
	var tabid = tab.get(0).id;
	if (tabid=='photo_tab_my') {
		$('#my_photos_menu').show();
		$('.tabs_hr').show();
	} else if (tabid=='photo_tab_free' || tabid=='photo_tab_new' || tabid=='photo_tab_shared') {
		$('#my_photos_menu').hide();
		$('.tabs_hr').hide();
	}
	
	try {
		CurrTab = tab.attr('id');
	} catch(ex) {
		Planetoid.debug(ex);
	}
	
	return true;
	
}

function selectSubTab(tab) {
	
	$('.sub_tab').css('font-weight',100).css('text-decoration','underline');
	
	tab.css('font-weight','900').css('text-decoration','none');
	
}

//Восстанавливает изначальный вид формы JS-upload
function JSUploadClearForm() {
	$('#test input').attr('disabled','false');
      	$('#uploadGo').attr('disabled','true').blur();
      	
   	document.getElementById('fileUploadForm').reset();
   	if ( $('div[id^=multi_] div').html() ) { 
   		$('div[id^=multi_] div').hide();
    		$('div[id^=multi_] div').queue(function(){
    			$('div[id^=multi_] div').html('');
    			$('#test').html('');
			$('#test').html('<input type="file" id="Image" name="Image" accept="gif|jpg|png" maxlength="3" class="multi" \/>');
			$.MultiFile();
    		});
   	} else {
   		$('#test').html('');
		$('#test').html('<input type="file" id="Image" name="Image" accept="gif|jpg|png" maxlength="3" class="multi" \/>');
		$.MultiFile();
   	}
}