function confirmLink(theLink, fmsg){
	if (typeof(window.opera) != 'undefined') 
		{return true;}
	var is_confirmed = confirm(fmsg);
	return is_confirmed;
}

function gebi(id) {return document.getElementById(id);}

function accept_ext(upload_field) {
    var extens = /\.txt|\.jpg|\.png|\.tif|\.bmp|\.zip|\.rar|\.arj|\.jpeg|\.docx|\.doc|\.xls|\.xlsx|\.pps|\.ppt|\.pdf|\.rtf|\.zip/i;
    var filename = upload_field.value;
    if (filename.search(extens) == -1) {
        alert("Только эти типы файлов можно загружать на сервер!\n"+"Доступно: .txt .jpg .png .tif .bmp .zip .rar .arj .jpeg .docx .doc .xls .xlsx .pps .ppt .pdf .rtf .zip");
        upload_field.value='';
        return false;
    }
    return true;
}

// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
function explode( delimiter, string ) {
	var emptyArray = { 0: '' }; 
	if ( arguments.length != 2 || typeof arguments[0] == 'undefined' || typeof arguments[1] == 'undefined' )
		{return null;}
 
	if ( delimiter === '' || delimiter === false || delimiter === null )
		{return false;}
	if ( typeof delimiter == 'function' || typeof delimiter == 'object' || typeof string == 'function' || typeof string == 'object' )
		{return emptyArray;}
	if ( delimiter === true )
		{delimiter = '1';}
    return string.toString().split ( delimiter.toString() );
}

function implode( glue, pieces ) {
	return ( ( pieces instanceof Array ) ? pieces.join ( glue ) : pieces );
}
function array_search( needle, haystack, strict ) {
	var strict = !!strict;
	for(var key in haystack){
		if( (strict && haystack[key] === needle) || (!strict && haystack[key] == needle) )
			{return key;}
  }
	return false;
}
//end of original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)


function array_del_el(arr,pos) {
 	arr.splice(pos,1);
	return arr;
}




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 setCookie(name, value, expiredays, path, domain, secure) {
	if (expiredays){
		var today = new Date();
		today.setTime( today.getTime() );
		expiredays = expiredays * 1000 * 60 * 60 * 24;
		var expires_date = new Date( today.getTime() + (expiredays));
	}
	document.cookie = name + "=" + escape(value) +
		((expiredays) ? "; expires=" + expires_date.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
}



function DeleteCookie (name) {
    var exp  = new Date();
    var cval = getCookie (name);

    exp.setTime (exp.getTime() - 1);  // This cookie is history
    document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}

//30 days
expire = 30;
// Reset the user's font size pref when the page is loaded
val = getCookie('selectedStyle');
if (val && val != 'undefined') {
	pickStyle(val);
}

function pickStyle(style) {
	var lastStyle = getCookie('selectedStyle');
	var ss = document.getElementById(lastStyle);
	if (ss)
		ss.disabled = true;
	setCookie('selectedStyle', style, expire);
	ss = document.getElementById(style);
	if (ss) {
		ss.disabled = true;
		ss.disabled = false;
	}
}



function addBookMark(title, url) {
	if (window.sidebar) {
		window.sidebar.addPanel(title, url, "");
	} else {
		if (window.external) {
			window.external.AddFavorite(url, title);
		} else {
			return true;
		}
	}
}

function addBookMark_() {
	addBookMark("E-BUN.MD", "http://e-bun.md");
}


function countDown(num,obj,info) {
	var len = num - obj.val().length;
	
	if( len >= 0 ){
		info.html(len);
	} else {
		obj.val(obj.val().substring(0, num));
		info.html(0);
	}
	return true;
}


var flg=2;
var lastmsg="";
function fash_msg(obj_id) {
	msg_obj=gebi(obj_id);
	if (flg == 2) {
		flg=1;
		lastmsg=msg_obj.innerHTML;
	}
	stime=1000;
	if ( flg == 1 ) {
		msg_obj.innerHTML="";
		flg = 0;
		stime=200;
	} else {
		msg_obj.innerHTML=lastmsg;
		flg = 1;
	}
	setTimeout("fash_msg('" + obj_id + "')",stime);
}



function html_entity_decode(str) {
	try {
		var tarea=document.createElement('textarea');
		tarea.innerHTML = str; return tarea.value;
		tarea.parentNode.removeChild(tarea);
  } catch(e) {
      //for IE add <div id="htmlconverter" style="display:none;"></div> to the page
		document.getElementById("htmlconverter").innerHTML = '<textarea id="innerConverter">' + str + '</textarea>';
		var content = document.getElementById("innerConverter").value;
		document.getElementById("htmlconverter").innerHTML = "";
		return content;
	}
}

function str_replace (search, replace, subject, count) {
	var i = 0, 
	 j = 0, 
	 temp = '', 
	 repl = '', 
	 sl = 0, 
	 fl = 0,
	 f = [].concat(search),
	 r = [].concat(replace),
	 s = subject,
	 ra = r instanceof Array, 
	 sa = s instanceof Array;
	 
	s = [].concat(s);	 
	if (count) {
		this.window[count] = 0;
	}
 
	for (i=0, sl=s.length; i < sl; i++) {
		if (s[i] === '') {
			continue;
		}
		for (j=0, fl=f.length; j < fl; j++) {
			temp = s[i]+'';
			repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
			s[i] = (temp).split(f[j]).join(repl);
			if (count && s[i] !== temp) {
				this.window[count] += (temp.length-s[i].length)/f[j].length;
			}
		}
	}
	return sa ? s : s[0];
}

var opnwindow = '';
function open_opnwindow( url , winname, opnwindow_width, opnwindow_height) {

	opnwindow = window.open( url, winname,
            'toolbar=0,location=0,directories=0,status=1,menubar=0,' +
            'scrollbars=yes,resizable=yes,' +
            'width=' + opnwindow_width + ',' +
            'height=' + opnwindow_height );

    if ( ! opnwindow.opener ) {
       opnwindow.opener = window.window;
    }

    if ( window.focus ) {
        opnwindow.focus();
    }

    return true;
}

function change_cats_type(value){
	var strrepl1, strrepl2, to_strrepl;
	
	if (value==0){
		to_strrepl = "tenders.html";
		strrepl1 = "users.html";
		strrepl2 = "offers.html";
	}else if (value==1){
		strrepl1 = "tenders.html";
		strrepl2 = "users.html";
		to_strrepl = "offers.html";
	}else if (value==3){
		gebi('left-box').style.display='none';
		$("#left-box-gsm").fadeIn("slow");
		return;
	}else{
		strrepl1 = "offers.html";
		strrepl2 = "tenders.html";
		to_strrepl = "users.html";
	}	
	
	if (gebi('left-box').style.display=='none'){
		gebi('left-box-gsm').style.display='none';
		$("#left-box").fadeIn("slow");
	}
	
	$("#left-box a").attr("href",function () {
			return $(this).attr("href").replace(strrepl1,to_strrepl).replace(strrepl2,to_strrepl);
		});
	if (! $("#left-box").is(":animated") && !$("#left-box").is(":hidden"))
		$("#left-box").fadeOut("fast").fadeIn("slow");
}


var indximg=0;
var images_array= new Array();
this.imgPreview = function(){	
		xOffset = -15;
		yOffset = 10;
	$("a.imgPreview").hover(function(e){
		//alert(images_array[$(this).attr("idx")].height);

		
		this.t = this.title;
		this.title = "";	
		var c = (this.t != "") ? "<br/>" + this.t : "";
		$("body").append("<div id='imgPreview'><img src='"+ images_array[$(this).attr("idx")].src +"' alt='' />"+ c +"</div>");								 
		$("#imgPreview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");		
    },
		function(){
			this.title = this.t;	
			$("#imgPreview").remove();
  }).each(function(){
  	var image = new Image();
  	images_array[indximg]=image;
  	$(this).attr("idx",indximg);
//		images_array[indximg].onload = function() {$("#imgPreview > img").attr("src", image.src);}

		images_array[$(this).attr("idx")].src = this.rel;
		indximg++;
	});	
  
	$("a.imgPreview").mousemove(function(e){
		var w = $(window);
		var offset_y_minus = w.height() - e.pageY + w.scrollTop() - images_array[$(this).attr("idx")].height - 20;
		if (offset_y_minus > 0)	{offset_y_minus=0;}
		
		$("#imgPreview")
			.css("top",(e.pageY - xOffset + offset_y_minus) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});
};



function console_log(str) {
	if (window.console != null) {
		console.log(new Date()+' ' + str)
	}
}

function importScript(url){
    var tag = document.createElement("script");
    tag.type="text/javascript";
    tag.src = url;
    document.body.appendChild(tag);
}

function get_typeof_page(id){
	var array = new Array("tender", "offer", "user","shop");
	return array[id];
}



$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});


var slideDownErrortimmer;
$.extend({
  slideDownError: function(error, timeout){
		if ($("#allert_bar").length == 0)
  		$("body").append('<div id="allert_bar">Пожалуйста, заполните все <span class="red">* красные</span> поля.</div>');
		var allert_bar = $("#allert_bar");
		allert_bar.html(error);
		allert_bar.slideDown(function(){
			allert_bar.css("backgroundColor", "#fe2b22");
			setInterval (function() { allert_bar.css("backgroundColor", "#fff"); }, 1000);
		});
		
		if (timeout){
			clearInterval(slideDownErrortimmer);
			slideDownErrortimmer = setInterval(function(){allert_bar.slideUp();}, timeout);
		}
	}
});


var search_query;
$(document).ready(function() {
	
	 $("input[defval], textarea[defval]")
		.blur(function(){if($(this).val() == '') $(this).val($(this).attr('defval')).css({'color':'#B7B7B7'});})
		.focus(function(){if($(this).val() == $(this).attr('defval')) $(this).val("").css({'color':'#000'});})
		.change(function(){if($(this).val() != $(this).attr('defval') && $(this).val() != '') $(this).css({'color':'#000'});});
		
	$("input[defval], textarea[defval]").blur();
  
  
	//< search tabs	
	

	$('#menu_cat_left').data('curridx', 0);
	$("#SearchTabs > ul > li a").click(
		function(event) {
			event.preventDefault();
			
			if ($(this).parent().hasClass("Current") && $('#menu_cat_left').data('curridx')!=0) {		
				return false;
			}
			$("#SearchTabs > ul > li").removeClass("Current");							 
			$(this).parent().addClass("Current");
			
			search_query=$.getUrlVar("q");
			if (! search_query) {$('#q').val("");}

			$('#q').attr("defval",$(this).attr("hint")).blur();


			var idx = $("#SearchTabs > ul > li a").index(this);

			$('#menu_cat_left').val(idx);
			if ($('#menu_cat_left').data('curridx')!=0)
				change_cats_type(idx);
			$('#menu_cat_left').data('curridx', 1);


			gebi('SearchPanel').action='/' + get_typeof_page(idx) + 's.html';
		}
	);
	$("#SearchTabs > ul > li a:eq("+$("#search_type").val()+")").trigger("click");
	
	$("#search_suggest a").click(
		function(event){
			$('#q').val($(this).text()).trigger("change");
			event.preventDefault();	
	})	
	
	//> search tabs
		

		//< Tooltips
		//+add
		$(".header > a[title], #save-session").tooltip({ 
			tip: '#dynatip', 
			offset: [-5, 4],
			effect: 'slide'
		}).dynamic( {
			bottom: {
				direction: 'down', 
				bounce: true
			}
		});
		//> Tooltips
	
	//LOGO
	var logo_size= new Array($("#logo").attr("width"), $("#logo").attr("height"));
    $("#logo").hover(
		function(){
			$(this).animate({ 
				width: (logo_size[0] * 15/14) + "px",
				height:  (logo_size[1] * 15/14) + "px",
				opacity: 0.8,
				marginLeft: "5px"
				}, 400 )},
		function () {
			$(this).stop();
			$(this).animate({ 
				width: logo_size[0] + "px",
				height: logo_size[1] + "px",
				opacity: 1.0,
				marginLeft: "0"
				}, 200 );
	  }
	)

	// typecat_menu selector
	$("#left-box > li:odd").css("background-color","#FEFDF5");
	
	//Table over tablesorter
	$(".table_ov").tablesorter({cssHeader : "th_header_sort"}); 
	
	$(".txtoverflow").ellipsis();
	
	imgPreview();

	$('.toggle').click(function(){togl($(this));});
	$('.toggle').each(function(){	if ($('#' + $(this).attr('rel')).is(":hidden"))	$(this).addClass('collapsed');});
	
});


function togl(el){
	var col_id = el.attr('rel');	
	if (el.hasClass('collapsed'))
	{
		el.removeClass('collapsed');
		$('#' + col_id).fadeIn(300)
		setCookie('collapse_' + col_id, 1, 1);
	}else{
		el.addClass('collapsed');
		$('#' + col_id).fadeOut(300);
		setCookie('collapse_' + col_id, 0, 1);
	}
}



function isEmpty(str,strict){
	if ( !strict ) str = str.replace(/^\s+|\s+$/g, '');
	return (str == null) || (str.length == 0);
}

function isEmail (email, strict)
{
	if(isEmpty(email,true)) return false;
	if ( !strict ) email = email.replace(/^\s+|\s+$/g, '');
	return (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(email);
}

function isNumeric(str){
	if(isEmpty(str)) return false;
	
	var re = /[\D]/g
	if (re.test(str)) return false;
	
	return true;
}

function goTop(a, t) {
	console_log( t);
	a = a || 0.1;
	t = t || 16;
	var x1 = 0;
	var y1 = 0;
	var x2 = 0;
	var y2 = 0;
	var x3 = 0;
	var y3 = 0;
	if (document.documentElement) {
		x1 = document.documentElement.scrollLeft || 0;
		y1 = document.documentElement.scrollTop || 0;
	}
	if (document.body) {
		x2 = document.body.scrollLeft || 0;
		y2 = document.body.scrollTop || 0;
	}
	var x3 = window.scrollX || 0;
	var y3 = window.scrollY || 0;
	var x = Math.max(x1, Math.max(x2, x3));
	var y = Math.max(y1, Math.max(y2, y3));
	var speed = 1 + a;
	window.scrollTo(Math.floor(x / speed), Math.floor(y / speed));
	if(x > 0 || y > 0) {
		var f = "goTop(" + a + ", " + t + ")";
		window.setTimeout(f, t);
	}
}
