// Make cross site scripting avaluable
document.domain = 'bikerspublic.com';

// Need to replace standart function
// because of all other libs use to encode characters.
// Now external libs will encode rus symbols as we wish
encodeURIComponent_back = encodeURIComponent;
encodeURIComponent = function(val) {
	return ruescape(val);
}

Date.prototype.parseDate = function (date, format) {
				if (date.constructor == Date) {
					return new Date(date);
				}
				var parts = date.split(/\W+/);
				var against = format.split(/\W+/), d, m, y, h, min, now = new Date();
				for (var i = 0; i < parts.length; i++) {
					switch (against[i]) {
						case 'd':
						case 'e':
							d = parseInt(parts[i],10);
							break;
						case 'm':
							m = parseInt(parts[i], 10);
							break;
						case 'Y':
						case 'y':
							y = parseInt(parts[i], 10);
							y += y > 100 ? 0 : (y < 29 ? 2000 : 1900);
							break;
						case 'H':
						case 'I':
						case 'k':
						case 'l':
							h = parseInt(parts[i], 10);
							break;
						case 'P':
						case 'p':
							if (/pm/i.test(parts[i]) && h < 12) {
								h += 12;
							} else if (/am/i.test(parts[i]) && h >= 12) {
								h -= 12;
							}
							break;
						case 'M':
							min = parseInt(parts[i], 10);
							break;
					}
				}
				return new Date(
					y||now.getFullYear(),
					(m||now.getMonth()+1)-1,
					d||now.getDate(),
					h||now.getHours(),
					min||now.getMinutes(),
					0
				);
			}

function FormPost(form_element, contaner_id, addp)
{
	var calb =  function(msg){};
	if (contaner_id) 
		calb = function(msg){ $("#"+contaner_id).html(msg); };
	FormSubmitEx(
		form_element, 
		"POST",  
		calb,
		addp
   	);
	return false;
}

function FormSubmitEx(form_element, method, callback, addp)
{
	fm = jQuery(form_element);
	var request = jQuery(fm).serialize();
	var action = fm.attr("action");
	if (addp)
	{
		if (request.length) request += "&";
		request += addp;
	}
	$.ajax({
	  	type: method,
	  	cache: false,
  		url: action,
  		data: request,
		success: function(msg){
     		callback(msg);
   		}
	});
	return false;
}
//
function FormClear(form_element)
{
	var fm = jQuery(form_element);
	fm.find(":text, :password, :file, textarea").val("");
	fm.find(":checked").removeAttr("checked");
	fm.find(":selected").removeAttr("selected");
	
}
// Reload all capcaha in portal
function CapchaReload(name)
{
	$("#capcha_"+name).attr({ src : "/cpt.php?t="+name+"&_=" + Math.random()} );
	$('#'+name+'_capcha').val('').focus();
}
// Show modal window 
function ShowModalWnd(element, source)
{
	if (!source)
		source = "ref";
	jQuery(element).createDialog({
   		addr: "@" + source,
   		progress: false,
   		bg: ""
	});
}


function localShowModalWnd(element_id)
{
	jQuery('').createDialog(
		{content: "#"+element_id,  progress: false, bg: '', local: true}
	);
}

// Goto href with ajax
// a_href - this a element
// contaner_id - html content of this contener will be replaced with ajax return (can be empty)
function ajaxHref(a_href, contaner_id, addp)
{
	var e = jQuery(a_href);
	var myurl = e.attr("href");
	var mydata = "";
	if (addp) mydata = addp
	func = function(msg) { };
	if (contaner_id)
	{
		func = function(msg) {$("#"+contaner_id).html(msg); };
	}
	$.ajax({
	  	type: 'GET',
	  	cache: false,
        data: mydata,
  		url: myurl,
		success: func 
	});
	return false;
}	

function block_resize(sel_el)
{
	$('*[name='+sel_el.name+']').val(sel_el.value);
	sel_el.form.onsubmit();
}

function block_resize_url(sel_el, base_url)
{
	var quant_name = sel_el.name;
	var quant_value = sel_el.value;
	var url = base_url + "&" + quant_name + "=" + quant_value;
	return GoTo(url);
}

function block_resize_ajaxurl(sel_el, contaner_id, base_url)
{
	var quant_name = sel_el.name;
	var quant_value = sel_el.value;
	var url = base_url + "&" + quant_name + "=" + quant_value;
	
	func = function(msg) { };
	if (contaner_id)
	{
		func = function(msg) {$("#"+contaner_id).html(msg); };
	}

	$.ajax({
	  	type: 'GET',
	  	cache: false,
  		url: url,
		success: func 
	});
	return false;
}
// Check message isn't empty, submit form with ajax
// make innerHTML for innerhtml_id element
// usage: onsubmit="return PostMessageForm(this, 'friend_meny')"
// if innerhtml_id not passed - there will not be innnerHTML 
function PostMessageForm(form_el, innerhtml_id)
{
	
	if ( trim(form_el.msg.value) == "")
	{
		var jq = jQuery(form_el);
		jQuery(form_el).find(".EmptyError").show();
		return false;
	}
	FormPost(form_el, innerhtml_id); 
	$.closeDialog(); 
	return false;
}

function under_construction()
{
	myalert("Under construction", "<b>Раздел сайт находится в разработке</b>");
	return false;
}
// Escape function for russian cp1251 charset
// Transform Николай -> %CD%E8%EA%EE%EB%E0%E9
var trans = [];
for (var i = 0x410; i <= 0x44F; i++)
	trans[i] = i - 0x350;
trans[0x401] = 0xA8;
trans[0x451] = 0xB8;
function ruescape(str)
{
	if (!str)
		return str;
	var ret = [];
	for (var i = 0; i < str.length; i++)
	{
		var n = str.charCodeAt(i);
		if (typeof trans[n] != 'undefined')
		n = trans[n];
		if (n <= 0xFF)
		ret.push(n);
	}
	var res = escape(String.fromCharCode.apply(null, ret));
	return res.replace(/\+/g, "%2B");
}

// trim string like php function
function trim(obj)
{
	if (obj.constructor.toString().indexOf("Array") != -1)
	{
		// trim array
		var len = obj.length;
		for (var i=0; i<len; ++i)
			obj[i] = obj[i].replace(/(^\s+)|(\s+$)/g, "");
		return obj;
	}
	else
		return obj.replace(/(^\s+)|(\s+$)/g, "");
}

// global bind
$(document).ready(function() {

	$('#myStatus').mouseover(function(){
		$(this).addClass('status_editable');
	}).mouseout(function(){
		$(this).removeClass('status_editable');
	}).click(function(){
		$(this).hide();
		$('#myStatusEdit').show();
		$('#myStatusEditInput').select().keydown(function(event){
			if (event.keyCode == 27)// On Escape
				$('#myStatusEditCancel').click();
		});
	});
	$('#myStatusEditSave').click(function(){
		$('#myStatusEdit').hide();
		$('#myStatus').html(tagfilter($('#myStatusEditInput').val())).show();
	});
	$('#myStatusEditCancel').click(function(){
		$('#myStatusEdit').hide();
		$('#myStatus').show();
	});
	init_sign_in();
	init_autocomplete();
	init_user_tips();
	init_club_tips();
	init_event_tips();
	$("#header_search_input").watermark({watermarkCssClass:"watermark"});
	if ($('#ply').length)
		$('._left_adv').remove();
});

function registration_ready() 
{
	$('#login').focus();
	$("#content :input").blur(
		function() { check_param(this.name); }
	).keyup( 
		function() { check_param_ok(this.name); }
	)
}
function init_sign_in()
{
	$('.signin').cluetip({
		cluetipClass: "auth",
		activation: 'click', 
		closePosition: null,
		dropShadow: false,
		width: 258, 
		//splitTitle: '|',
		sticky: true,
		showtitle: false,
		attribute: false,	//no attribute for getting content
		onShow: function() {
				$("#cluetip-inner").load("/auth.php?ajax=");
		}
	});
}

function init_autocomplete()
{
	var elements = $(':input[@suggest_for]');
	var def_opt = {selectFirst: true, minChars: 1, selectFirst: true};
	for (var i=0; i<elements.length; ++i)
	{
		var e = $(elements[i]);
		var for_str = e.attr('suggest_for');
		if (for_str == 'user_city')
			e.autocomplete("/autocomplete.php?t=city_u", def_opt);
		else if (for_str == 'club_city')
			e.autocomplete("/autocomplete.php?t=city_c", def_opt);
		else if (for_str == 'user_country')
			e.autocomplete("/autocomplete.php?t=country_u", def_opt);
		else if (for_str == 'club_country')
			e.autocomplete("/autocomplete.php?t=country_c", def_opt);
	}

}

function init_user_tips()
{
	var tips = $('*[@user_tip]');
	for (var i=0; i<tips.length; ++i)
	{
		var t = $(tips[i]);
		var id = t.attr('user_tip');
		t.attr("user_hint_rel", "/uinf.php?u=" + id );
		
		t.cluetip({
			cluetipClass: "hint",
			activation: 'hover', 
			closePosition: null,
			dropShadow: false,
			width: 250, 
			local: false,
			positionBy : 'auto',
			showtitle: false,
			mouseOutClose: false,
			attribute: "user_hint_rel",
			hoverIntent: false//{sensitivity: 30, interval: 50, timeout: 200}
		});
	}

}

function init_club_tips()
{
	var tips = $('*[@club_tip]');
	for (var i=0; i<tips.length; ++i)
	{
		var t = $(tips[i]);
		var id = t.attr('club_tip');
		t.attr("club_hint_rel", "/cinf.php?club_id=" + id );
		
		t.cluetip({
			cluetipClass: "hint",
			activation: 'hover', 
			closePosition: null,
			dropShadow: false,
			width: 250, 
			local: false,
			positionBy : 'auto',
			showtitle: false,
			mouseOutClose: false,
			attribute: "club_hint_rel",
			hoverIntent: false//{sensitivity: 30, interval: 50, timeout: 200}
		});
	}

}

function init_event_tips()
{
	var tips = $('*[@event_tip]');
	for (var i=0; i<tips.length; ++i)
	{
		var t = $(tips[i]);
		var id = t.attr('event_tip');
		t.attr("event_hint_rel", "/einf.php?event_id=" + id );
		
		t.cluetip({
			cluetipClass: "hint",
			activation: 'hover', 
			closePosition: null,
			dropShadow: false,
			width: 250, 
			local: false,
			positionBy : 'auto',
			showtitle: false,
			mouseOutClose: false,
			attribute: "event_hint_rel",
			hoverIntent: false//{sensitivity: 30, interval: 50, timeout: 200}
		});
	}

}

function check_param(inp_name)
{
	var value = $("#"+inp_name).val();
	$.post("?", {ajax : "", name: inp_name, val: value},  
		function(err_msg)
		{
			var name = inp_name;
			$("#"+name +"_error div").hide();
			if (err_msg == "" || err_msg == "undef")
				return;
			$("#"+err_msg).show();
		}
	);
}

function check_param_ok(inp_name)
{
	var value = $("#"+inp_name).val();
	if (value == "")
		return;
	$.post("?", {ajax : "", name: inp_name, val: value},  
		function(err_msg)
		{
			var name = inp_name;
			if (err_msg == "")
				$("#"+inp_name +"_error div").hide();
		}
	);
}


function del_comment(el, container)
{
	ajaxHref(el, container, 'ajax=');
}

function focus_search(el)
{
	if (el.value == el.title)
		el.value = '';
}
function blur_search(el)
{
	if (el.value == '')
		el.value = el.title;
}

function get_title(id){return 	$('#'+id+' .title').html();}
function get_body(id){return 		$('#'+id+' .body').html();}

function tagfilter(str) 
{
	str = str.replace(/&/g, "&amp;");
	str = str.replace(/</g, "&lt;");
	str = str.replace(/>/g, "&gt;");
	str = str.replace(/#/g, "&#35;");
	str = str.replace(/"/g, "&quot;");
	str = str.replace(/'/g, "&#39;");
	str = str.replace(/@/g, "&#064;");
	return str;
}

function untagfilter(str) 
{
	str = str.replace(/&#37;/g, "%");
	str = str.replace(/&#39;/g, "'");
	str = str.replace(/&quot;/g, "\"");
	str = str.replace(/&#35;/g, "#");
	str = str.replace(/&gt;/g, ">");
	str = str.replace(/&lt;/g, "<");
	str = str.replace(/&amp;/g, "&");
	str = str.replace(/&#64;/g, "@");
	return str;
}

function load_index_block(block, sub)
{
	var a = $('#' + block + '_block').load("index.php?ajax=1&block=" + block + "&subblock=" + sub);
	return false;
}

function clearStars(el)
{
	var parent = $(el.parentNode);
	var childs = parent.children("a");
	for(var i=0; i<childs.length; ++i )
	{
		var img = $(childs[i]).children("img");
		img = $(img[0]);
		img.attr("class", img.attr("baseclass") );
		img.removeAttr("baseclass")
	}
}

function showStars(el, star) {
	var parent = $(el.parentNode);
	var childs = parent.children("a");
	for(var i=0; i<childs.length; ++i )
	{
		var img = $(childs[i]).children("img");
		img = $(img[0]);
		if (!img.attr("baseclass"))
			img.attr("baseclass", img.attr("class"));
		if (i >= star)
			img.attr("class", "star_empt_16");
		else
			img.attr("class", "star_full_16");
	}
}

function setStars(el, star) {
	var parent = $(el.parentNode);
	var p_id = "";
	if (! parent.attr("id")) {
		p_id = "_rank" + parseInt(Math.random()*10000);
		parent.attr("id", p_id)
	}
	else
		p_id = parent.attr("id");
	var content_id = parent.attr("content_id");
	var rank_type = parent.attr("rank_type");
	var star_num = star + "";
	$.get("rank.php", {vote: star_num, type: rank_type, cid: content_id}, function(data) {
		$("#" + p_id).html(data);
	});
}

function GoTo(href)
{
	window.location = href;
	return false;
}

jQuery.fn.outerHtml = function()
{
	// Simple function that returns string with not inner html contents, but with outer
	// It is usefull for getting <img>-tag html-code, or other tags that has no content, or has it.
	var el = $(this);
	var html = el.wrap('<p></p>').parent().html();
	el.parent().html(html);
    return html;
}
