function getById(id){
	return document.getElementById(id);
}

/*networking info*/
var file_name = 'location.php';
var tmp_text = 'loading';
function changeSubField(id_field){

	role_obj = getById('role');
	role_obj.innerHTML = '';

	str = 'sel=get_netw_fields&par=id_sub_field&id_spr='+id_field;
	destination_obj = getById('sub_field');
	anisochronous = true;
	ajaxRequest(file_name, str, destination_obj, tmp_text, anisochronous);
}
function changeRole(id_sub_field){
	str = 'sel=get_netw_fields&par=id_role&id_spr='+id_sub_field;
	destination_odj = getById('role');
	anisochronous = true;
	ajaxRequest(file_name, str, destination_odj, tmp_text, anisochronous);
}

function logoffAfter(sec){
	setTimeout(function(){location.href='index.php?sel=auto_logoff'},(sec*1000));
}
function closeAfter(sec){
	setTimeout(function(){window.close();},(sec*1000));
}

function showNotice(msg){
	if (!msg) return;
	//$("<div id='temp'>"+msg+"</div>").appendTo("body").addClass("notice_div").fadeIn("slow").fadeTo(2000,1).fadeOut("slow");
}

function getJQData(data){
	if (!data){
		showNotice('system error!!!');
		return false;
	}
	var resp;
	try{
		resp = eval('('+data+')');
	}catch(e){
		resp = '';
	}
	if (!resp){
		showNotice('system error!!!');
		return false;
	}
	return resp;
}

function ajaxLoadingImage(status, id_container){
	if (status)
		$("#"+id_container).html('<img id="img_loading" src="'+TEMPLATE_PATH+TEMPLATE_IMAGES_ROOT+'/ajax-loader.gif" alt="" border="0" />');
	else
		$("#"+id_container).html('');
}


function addTag(id_item){
	var file_name;
	var input_tag_val;
	file_name = $("#file_name").val();
	input_tag_val = $("#input_tag"+id_item).val();
	str = "ajax=1&sel=addtag&tag="+input_tag_val+"&id_item="+id_item;
	$.post(file_name, str, afterAddTag);
}

function afterAddTag(data){
	if (!data) return;
	var resp;
    resp = eval('('+data+')');
    if (!resp) return;
	showNotice(resp["msg"]);
	if (resp["code"] == '1'){
		var id_item
		id_item = resp['id_item'];

		/*$("#all_tags_container"+id_item).show();*/
		$("#my_tags_container"+id_item).show();
		$("#input_tag"+id_item).val('');
		$.each(resp['tags_info'], function(i, n){
			/*$("#all_tags"+id_item).append('<span><a href="'+n.search_link+'" title="'+n.tag_count+'">'+n.tag+'</a>&nbsp;&nbsp;</span>').css('display','none').fadeIn("slow");*/
			$("#my_tags"+id_item).append('<span id="my_tag'+n.id+'">'+n.tag+'&nbsp;<a href="#" onclick="delTag(\''+n.id+'\'); return false;" class="del_x_link">x</a>&nbsp;&nbsp;</span>').css('display','none').fadeIn("slow");
		});
	}
}

function delTag(id){
	file_name = $("#file_name").val();
	data = 'ajax=1&sel=deltag&id='+id;
	$.post(file_name, data, afterDelTag);
}

function afterDelTag(data){
	if (!data) return;
	var resp;
    resp = eval('('+data+')');
    if (!resp) return;
	showNotice(resp["msg"]);
	if (resp["code"] == '1'){
		$('#my_tag'+resp.id_tag).fadeOut('fast');
	}
}

function bookmarkSitePage(page_link, type, descr){
	page_link = escape(page_link);
	str = 'ajax=1&bookmark_url='+page_link+'&bookmark_type='+type+'&bookmark_descr='+descr;
	$.post('organizer.php?sel=bookmark_site_page',str, function(data){
		var resp = getJQData(data);
		if (!resp) return;
		showNotice(resp["msg"]);
	});
}

function checkLoginDublicate(login, fname, file_name, id_source, id_destination){
	$("#"+id_destination).empty();
	if (login.length < 5) return false;
	str = 'ajax=1&sel=check_login_dublicate&login='+login+'&fname='+fname;
	$.post(file_name, str, function(data){
		var resp = getJQData(data);
		if (!resp) return;
		var html_code='';
		if (resp.msg != undefined){
			html_code += '<font class="error_msg">'+resp.msg+'</font>';
		}
		if (resp.data){
			///such login already exist
			$.each(resp.data, function(i,val){
				html_code += '<br /><a href="#" onClick="$(\'#'+id_source+'\').val(\''+val+'\'); $(\'#'+id_destination+'\').empty(); $(\'#'+id_source+'\').focus();" >'+val+'</a>';
			});
		}
		if (html_code != ''){
			$("#"+id_destination).append(html_code);
		}
	});
}

function abuseReportForm(){
	if ($("#abuse_form_parent").html() && $("#abuse_form_parent").remove()) return;
	$("#abuse_link").before("<div id='abuse_form_parent' style='display:inline; position:absolute;bottom:45px;'>"+$("#abuse_form_tpl").html()+"</div>");
	$("#abuse_form").addClass('abuse_form');
	var height = ($("#abuse_form").height()+$("#abuse_link").height());
	$("#abuse_form").css('bottom','25px');
	$("#abuse_form").css('left','0px');
	$("#abuse_form").css('width','145px');

}

function sendAbuseReport(id_user, id_item, type_item){
	var type_msg = $("input[name='ab_type_msg']:checked").attr('value');
	var msg = $("#ab_msg").val();
	if (!id_user || !id_item || !type_item || !type_msg || !msg) return;
	str = 'ajax=1&sel=save_abuse_report&id_user='+id_user+'&id_item='+id_item+'&type_item='+type_item+'&type_msg='+type_msg+'&msg='+msg;
	$.post(SEO_SITE_ROOT+"/backend.php", str, function(data){
		$("#abuse_form").html(data);
		var height = ($("#abuse_form").height()+$("#abuse_link").height());
		$("#abuse_form").css('bottom','20px');
		$("#abuse_form").css('left','0px');
		$("#abuse_form").css('white-space','nowrap');
		$("#abuse_form").fadeIn('fast').fadeTo(1000,1).fadeOut(2000,function(){$("#abuse_form_parent").remove()});
	})
}

function answerPoll(poll_id){
	launchWindow(SEO_SITE_ROOT + '/poll.php?sel=vote_poll&ajax=1&greybox=1&poll_id='+poll_id, '', 370, 400);
	return;
}

function addPoll(){
	if (window.poll_from_param === undefined){
		poll_from_param='';
	}
	launchWindow(SEO_SITE_ROOT + '/poll.php?sel=add_poll_form&ajax=1&par='+poll_from_param, '', 600, 690);
}

function getRandColor(){
	min=0;
	max=16777215;
	random_int = getRandom(min,max);
	rand_color_hex = d2h(random_int);
	return rand_color_hex;
}

function getRandom(min,max){
	rand = Math.floor(min+(max-min)*Math.random());
	return rand;
}

function d2h(d) {
	return d.toString(16);
}

function h2d(h) {
	return parseInt(h,16);
}

function showNoticeOnEl(msg,jq_obj_el){
	if (!msg) return
	var offset = jq_obj_el.offset();
	var x = offset.left;
	var y = offset.top;
	var rand = Math.random()*10;
	var rand_str = rand.toString();
	rand = rand_str.replace(".","");
	$("<div id='temp"+rand+"'>"+msg+"</div>").appendTo("body").addClass("notice_div1_on_el").fadeIn("slow").fadeTo(2000,1).fadeOut("slow",function(){});
	$("#temp"+rand).click(function(){
		$(this).remove();
	});
	$("#temp"+rand).css("top",(y+15)+"px");
	$("#temp"+rand).css("left",(x+5)+"px");
}

function showVGCommentOnEl(id_gift, msg,jq_obj_el){
	if (!msg) return
	var offset = jq_obj_el.offset();
	var x = offset.left;
	var y = offset.top;
	var rand = Math.random()*10;
	var rand_str = rand.toString();
	rand = rand_str.replace(".","");

	if (comment_enabled[id_gift]){
		comment_enabled[id_gift]=0;
		$("#temp"+id_gift).remove();
	}else{
		comment_enabled[id_gift]=1;
		$("<div id='temp"+id_gift+"'>"+msg+"</div>").appendTo("body").addClass("notice_div1_on_el").fadeIn("slow").fadeTo(2000,1);
		$("#temp"+id_gift).click(function(){
			comment_enabled[id_gift]=0;
			$(this).remove();
		});
		$("#temp"+id_gift).css("top",(y+14)+"px");
		$("#temp"+id_gift).css("left",x+"px");
	}

}
jQuery.fn.center = function () {
	var window_height = window.innerHeight ? window.innerHeight : $(window).height();
	var window_width = window.innerWidth ? window.innerWidth : $(window).width();
	this.css("position","absolute")
		.css("top", (window_height - this.height() < 0 ? 10 : window_height - this.height() ) / 2+$(window).scrollTop() + "px")
		.css("left", (window_width - this.width() < 0 ? 10 : window_width - this.width() ) / 2+$(window).scrollLeft() + "px");
	return this;
}

function launchWindow(file, str, width, height, center, fixed_size) {
	fixed_size = fixed_size || false;
	if (center != true){
		center = false;
	}
	var window_height = window.innerHeight ? window.innerHeight : $(window).height();
	var window_width = window.innerWidth ? window.innerWidth : $(window).width();
	
	var maskHeight = window_height;
	var maskWidth = window_width;

 	if(height != undefined && height > 0){
		if (window_height < height && !fixed_size) height= window_height-40;
	}
	if(width != undefined && width > 0){
		if (window_width < width && !fixed_size) width = window_width-40;
	}
	ajaxLoadingImage(1, 'content');

	if(file != '')
	$.post(file, str+'&async=false&rand='+Math.random(), function(data){
		if (data == ''){
			return;
		}
		$('#mask').css({'opacity': 0.7});
		$('#mask').fadeIn(300);
		$('.window').css('padding','0px');
		if(!data.match(/<h2>|<H2>/)){
			$('.window >div > #close > div').attr('class','close_icon_red');
		}else{
			$('.window >div > #close > div').attr('class','close_icon_white');
		}
		$('#content').html(data);
		$('.window').css({'width':width});
		if(str != 'sel=loginform' && !(/lost_pass/).test(file) && !(/index.php/).test(file)){
			$('.window').center();
		}
		if ((/.*(myprofile\.php)/.test(file) || /.*(viewprofile\.php)/.test(file)) && center == false){
			$('.window').css('top', '10px');
		}
		$('.window').fadeIn(300);
		if($('.window').position().top < 10){
			$('.window').css('top','10px');
		}

		if($('.window').position().top - $(window).scrollTop() < 0){
			$('html, body').animate({scrollTop: $('.window').position().top-10}, 100);
		}
	});
return;
}

/*
function launchInvite(width, height) {

	var maskHeight = $(document).height();
	var maskWidth = $(window).width();

        
	$('#mask').css({'width':maskWidth,'height':maskHeight,'opacity': 0.7});
	$('#mask').fadeIn(300);

	if(height != undefined && height > 0){
		if ($(window).height() < height) height= $(window).height()-70;
	}
	if(width != undefined && width > 0){
		if ($(window).width() < width) width = $(window).width()-70;
	}
	ajaxLoadingImage(1, 'content');

	$('.window').css({'width':width});
	$('.window').center();
	$('.window').fadeIn(300);
return;
}
*/
function launchWindowAlbums(file, str, width, height) {

	var window_height = window.innerHeight ? window.innerHeight : $(window).height();
	var window_width = window.innerWidth ? window.innerWidth : $(window).width();
	var maskHeight = $(".wrapper").height();
	var maskWidth = window_width;
 
	$('#mask').css({'width':maskWidth,'height':maskHeight,'opacity': 0.7});
	$('#mask').fadeIn(300);

	if(height != undefined && height > 0){
		if (window_height < height) height = window_height-40;
	}
	if(width != undefined && width > 0){
		if (window_width < width) width = window_width-40;
	}
	ajaxLoadingImage(1, 'content');

	if(file != '')
	$.post(file, str, function(data){
		$('.window').css('padding','0px');
		if(!data.match(/<h2>|<H2>/)) $('.window >div > #close > div').attr('class','close_icon_red');
		else $('.window >div > #close > div').attr('class','close_icon_white');
		$('#content').html(data);
		$('.window').css({'width':width});
		$('.window').center();
		$('.window').fadeIn(300);
		
	var resp = getJQData(data);
		if (resp['id'] > 0) {
			GetComments(resp['id'], 1);
		}
	});
return;

}

function GetComments(id, page) {
    $('.comments_links_gallary').html('');
    $('#comments').css({'height':$('#comments').height()});
    ajaxLoadingImage(1, 'comments');
    $.post(SEO_SITE_ROOT+'/gallary.php', {sel:'get_comments', id:id, page:page}, function(resp){
        if (resp['err'] != undefined) {
             $('#comments').html('<div id="error_msg" class="error_msg">'+resp['err']+'<\/div><div>&nbsp;</div>');
        } else {
            $('#comments').html('');
            $('.comments_links_gallary').css({'height':'20px'});
            for ( var i=0;i<resp['count'];i++) {
                $('#comments').append("<div class='comment_upload'><div class='comment_author'>"+resp[i]["name"]+" ("+resp[i]["date_post"]+")<\/div><div class='comment_message'>"+resp[i]["comment"]+"<\/div><\/div>");
            }
            for ( i=0; i<resp['links'].length; i++) {
                if (resp['links'][i]['sel'] == 1)
                    $('.comments_links_gallary').append("<span style='font-weight: bold;padding: 0px 5px;'>"+resp['links'][i]['link']+"<\/span>");
                else 
                    $('.comments_links_gallary').append("<span style='cursor:pointer;padding: 0px 5px;' onclick='GetComments("+id+", "+resp['links'][i]['val']+")'>"+resp['links'][i]['link']+"<\/span>");
            }
        }
        $('#comments').css({'height':'100%'});
    },
	'json'
	);
}

function GetComments_myprofile(id, page, can_edit, without_img) {
	without_img = without_img || 0;
	$('.comments_links_gallary').html('');
    $('#comments').css({'height':$('#comments').height(), 'width':'420px', 'padding-top':'10px', 'display':'table'});
	$('.hotornot').css('display','none');
    ajaxLoadingImage(1, 'comments');
        
    $.post(
		SEO_SITE_ROOT+'/myprofile.php', 
		{
			sel:'get_comments', 
			id:id, page:page, 
			can_edit: can_edit
		}, 
		function(resp){
			if (resp['err'] != undefined) {
				 $('#comments').html('<div id="error_msg" class="error_msg">'+resp['err']+'<\/div><div>&nbsp;</div>');
			} else {
				/*$('#comments').html('');
				if (resp['count'])
					$('.comments_links_gallary').append("<span>"+resp['showing']+" "+resp['page']+" "+resp['of']+" "+resp['count_page']+"</span>");
					$('.comments_links_gallary').css({'height':'20px', 'width':'420px', 'display':'table'});
				for (var i=0;i<resp['count'];i++) {
					var comment_html = "<div class='comment_upload' style='padding-bottom:5px;display:table;width:100%;'><div class='comment_author'>";
					if(!without_img) comment_html += "<img style='margin-right:5px;' class='icon imgcanvas float_left' src='"+resp[i]["icon_path"]+"'>";
					comment_html += "<div class='float_left' style='width:305px;'><a href='"+resp[i]["profile_link"]+"'>"+resp[i]["name"]+"</a> ("+resp[i]["date_post"]+"): &nbsp;&nbsp;&nbsp; <a style='cursor: pointer;' onclick='DeleteUploadComment(this, "+resp[i]["id_comment"]+");' >"+resp[i]["del_lang"]+"</a> <p class='comment_message'>"+resp[i]["comment"]+"<\/p><\/div><\/div>";
					$('#comments').append(comment_html);				
				}

				var page = resp['page'];
				if(resp.links){
					if (typeof(resp['links'][page-1])!=='undefined' && resp['links'][page-1]['previous_page'] == 1){
						$('.comments_links_gallary').append("<a href='javascript: void(0);' onclick='GetComments_myprofile("+id+", "+(resp['links'][page-1]['val'])+", "+can_edit+", "+without_img+")' class='back-page-act' id='back-page-act_top'>&nbsp;</a>");
					}else{
						$('.comments_links_gallary').append("<a href='javascript: void(0);' class='back'>&nbsp;</a>");
					}
					if (typeof(resp['links'][page+1])!=='undefined' && resp['links'][page+1]['next_page'] == 1){
						$('.comments_links_gallary').append("<a href='javascript: void(0);' onclick='GetComments_myprofile("+id+", "+(resp['links'][page+1]['val'])+", "+can_edit+", "+without_img+")' class='next-page-act' id='next-page-act_top'>&nbsp;</a>");
					}else{
						$('.comments_links_gallary').append("<a href='javascript: void(0);' class='next'>&nbsp;</a>");
					}
				}*/
				
				$('#comments_div').html(resp.comments);
				
				//vote
				if (resp['rating'] != 1){
					$('.hotornot').css('display','table');
					$('.hotornot').html('<div onclick="VoteUser_myrpofile('+resp['vote'][0]+');" class="rate_heart rate_heart_inactive" id=mark'+resp['vote'][0]+' name=mark'+resp['vote'][0]+' onmouseover="marks('+resp['vote'][0]+',\'show\');" onmouseout="marks('+resp['vote'][0]+',\'hide\');"></div>');
					for (var i=1; i<resp['vote'].length;i++){
						$('.hotornot').append('<div onclick="VoteUser_myrpofile('+resp['vote'][i]+');" class="rate_heart rate_heart_inactive" id=mark'+resp['vote'][i]+' name=mark'+resp['vote'][i]+' onmouseover="marks('+resp['vote'][i]+',\'show\');" onmouseout="marks('+resp['vote'][i]+',\'hide\');"></div>');
					}
				}
				else{$('.hotornot').css('display','none');}
				
			}
			//$('#comments').css({'height':'100%'});
		},
		'json'
	);
}

$(document).ready(function() {
    $('#send_comment').live("click", function (e) {
        var height_comment = $('#comments').height();
        $('#comments').css({'height':height_comment});
        var message = $('#message').val();
        var id = $('#id_upload').val();
		var type = $('#upload_type').val();
        if (message != '' && id > 0)
        $.post(SEO_SITE_ROOT+'/gallary.php', {sel:'set_comment', id:id, message:message}, function(data){
            if (data == 'send'){
                $('#error_msg').html('');
                $('#comments').html('');
                $('#message').val('');
				document.location = SEO_SITE_ROOT + '/gallary.php?sel=view_upload&upload_type='+type+'&id='+id;
            }
			else{
				$('#error_msg').html(data);
			}
        });
    });
});

function UpdateResult(result_div, request, data){
	data = data || '';

	$.ajax({
		type: "POST",
		url: request,
		data: "ajax=1"+data,	   
		ajaxStart: UpdatingProcess(result_div),
		success: function(msg){
			//msg_arr = msg.split("REQUEST_DELIMITER");
			$("#update_div").remove();
			$("#update_img").remove();   			
			ajaxLoadingImage(0, result_div)
			$("#"+result_div).html(msg);
		}
	});   
}

function UpdatingProcess(div){
	$("#update_div").remove();
	//$("#update_text").remove();
	$("#update_img").remove();
	$div_el = $("#"+div);
	var width = $div_el.width();
	var height = $div_el.height();
	var left_pos = $div_el.offset().left;	   			
	var top_pos = $div_el.offset().top;
	$("body").append('<div id="update_div"></div>');
	$("#update_div").css("z-index", 9995)
				.css("position", "absolute")
				.css("left", left_pos)
				.css("top", top_pos)
				.css("width", width)
				.css("height", height)
				.css("border", "0px solid #cccccc")
				.css("background-image", "url('"+bg_img+"')");
	
	var left_img = left_pos + width/2 - 16;
	var left_text = left_pos + width/2 + 24;
	var top_img = top_pos + height/2 -16;	
	var top_text = top_img + 8;	
	$("body").append("<img id='update_img' src='"+indicator+"' style='position:absolute;z-index:9996; left: "+left_img+"px;top: "+top_img+"px;'>");
	//$("body").append("<div id='update_text' style='position:absolute;z-index:9996; left: "+left_text+"px;top: "+top_text+"px;'>"+update_text+"</div>");
						
};

function marks(id,type){
	if (!document.images) return false;
	for (i=1; i<=id; i++){
		if (type=="show"){
			$("#mark"+i).removeClass("rate_heart_inactive");
			$("#mark"+i).addClass("rate_heart_active");
		}
		else if (type=="hide"){
			$("#mark"+i).removeClass("rate_heart_active");
			$("#mark"+i).addClass("rate_heart_inactive");
		}
	}
	return;
}


function changeAdultAllow(cb, callback){
	callback = callback || function(){};
	var adult_allow = $(cb).is(':checked') ? 1 : 0;
	$.post(
		SERVER+'/ajax_backend.php',
		{sel: 'change_adult_allow', adult_allow: adult_allow},
		callback,
		'json'
	);
}
