var sf_val, sf_id=0;
function nc_comm_del(ee, fnid){
	ajaxpoploading();
	var data = 'task=comment&status=delete&fnid='+fnid;
	$.ajax({
		type: 'POST',
		url: '/ajax/main.php',
		data: data,
		success: function(response){
			//returnProcessJSON(response);
			closepopup();
			$(ee).parents("li .comment_"+fnid).remove();
		}
	});
}
function searchContent(cat, page){
	var search = $('#contentname').val();
	if(sf_val!=search){
		sf_val = search;
		sf_id += 1;
		$('#results').html('');
		filesAPage(cat, page, search, sf_id);
	}
}
function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};
parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

function hideReferrer(e){
	e.returnValue ? e.returnValue = false : e.preventDefault();
	var win = window.open("");
	win.location.href = "javascript:location.replace('" + e.target + "')";
	return false;
}
function clickNotiItem(url){
	//var urlObj = parseUri(window.location);
	var qindex = url.indexOf('?');
	if(parseUri(window.location).path=='/home.php'){
		if(qindex==-1){
			window.location = '#'+url;
			LMOnclick(url, true);
		}else{
			window.location = url;
		}
	}else{
		if(qindex==-1){
			window.location = '/home.php?task='+url;
		}else{
			window.location = url;
		} 
	}
	$("#fbNotificationsJewel" ).click();
}
function clickMessageItem(code){
	$("#fbMessagesJewel" ).click();
	LMOnclick('message&code='+code, true);
}
function noti_notifications(){
	val = $("#fbNotificationsFlyout #FlyoutBody").html();
	if(val=='' || val==' '){
		//LMOnclick('notification&status=response', true);
		//ajaxpoploading();
		var data = 'task=notification&status=response';
		$.ajax({
			type: 'POST',
			url: '/ajax/main.php',
			data: data,
			success: function(response){
				$('#fbNotificationsList').addClass('hidden_elem');
				$('#fbNotificationsFlyout #FlyoutBody').html(response);
			}
		});
	}
}
function noti_messages(){
	val = $("#fbMessagesFlyout #FlyoutBody").html();
	if(val=='' || val==' '){
		//LMOnclick('notification&status=response', true);
		//ajaxpoploading();
		var data = 'task=notification&status=messages';
		$.ajax({
			type: 'POST',
			url: '/ajax/main.php',
			data: data,
			success: function(response){
				$('#fbMessagesFlyout #FlyoutBody').html(response);
				$('#fbMessagesList').addClass('hidden_elem');
			}
		});
	}
}
function noti_requests(){
	val = $("#fbRequestsFlyout #FlyoutBody").html();
	if(val=='' || val==' '){
		//LMOnclick('notification&status=response', true);
		//ajaxpoploading();
		var data = 'task=notification&status=requests';
		$.ajax({
			type: 'POST',
			url: '/ajax/main.php',
			data: data,
			success: function(response){
				$('#fbRequestsFlyout #FlyoutBody').html(response);
				$('#fbRequestsList').addClass('hidden_elem');
			}
		});
	}
}
function ch_start(){
	var t = setInterval("ch_recieve_list()", 1500);
}
function scroll_compute(){
	var spath = document.documentElement.scrollHeight - document.body.clientHeight; 
	var vscroll = (document.all ? document.scrollTop : window.pageYOffset);
	var lpath = spath - vscroll;
	if(lpath>300){
		return true;
	}else{
		return false;
	}
}
function ch_recieve_list(){
	var data = 'task=chat&status=online';
	$.ajax({
		type: 'POST',
		url: '/ajax/main.php',
		data: data,
		success: function(response){
			$('#chat_online').html(response);
		}
	});
}
//ch_start();
function searchMessages(){
	var search = $('#MessagingQuery').val();
	if(sf_val!=search){
		sf_val = search;
		sf_id += 1;
		$('#MessagingThreadlist').html('');
		messagesAPage(0, search, sf_id);
	}
}
function messagesAPage(page, search, lsf_id){
	ajaxpoploading();
	var data = 'task=message&status=ajaxpage&page='+page+'&search='+search;
	$.ajax({
		type: 'POST',
		url: '/ajax/main.php',
		data: data,
		success: function(response){
			if(sf_id==lsf_id){
				$('#pagelet_stream_pager').remove();
				$('#MessagingThreadlist').append(response);
			}
			closepopup();
		}
	});
}
function msg_isread(ee, stat, code){
	//ajaxpoploading();
	var data = 'task=message&status=isread&code='+code+'&isread='+stat;
	$.ajax({
		type: 'POST',
		url: '/ajax/main.php',
		data: data,
		success: function(response){
			if(response=='true'){
				$(ee).parents('li').toggleClass('unread');
			}
		}
	});
}
function msg_archive(ee, code){
	var data = 'task=message&status=archive&code='+code;
	$.ajax({
		type: 'POST',
		url: '/ajax/main.php',
		data: data,
		success: function(response){
			if(response=='true'){
				$(ee).parents('li').remove();
			}
		}
	});
}
$(function() {
	$("#fbNotificationsJewel" ).toggleMenu({body:'#fbNotifications'});
	$("#fbMessagesJewel" ).toggleMenu({body:'#fbMessages'});
	$("#fbRequestsJewel" ).toggleMenu({body:'#fbRequests'});
});
(function( $ ){
    $.fn.toggleMenu = function(options) {
        var mbody=options['body']+'Flyout';
        var mjewel=options['body']+'Jewel';
        var hidden=true;
        var menu=this;
        $(this).click(function(e) {
            if(hidden){
                $(mbody).toggleClass('toggleTargetClosed');
                $(this).addClass('openToggler');
                $(this).removeClass('hasNew');
                hidden=false;
            }else{
                $(mbody).addClass('toggleTargetClosed');
                $(this).removeClass('openToggler');
                hidden=true;
            }
        });
        $(mbody).mouseup(function() {
            return false;
        });
        $(document).mouseup(function(e){
            if($(e.target).parent(mjewel).length==0){
                $(mbody).addClass('toggleTargetClosed');
                $(menu).removeClass('openToggler')
                hidden=true;
            }
        });
    };
})( jQuery );
(function( $ ){
    $.fn.toggleButton = function(el_id) {
        var hidden=true;
        var menu=this;
        $(this).click(function(e) {
            if(hidden){
                $(el_id).addClass('openToggler');
                $(this).addClass('selected');
                //$(this).parent('.wrap').toggleClass('openToggler');
                //$(this).removeClass('hasNew');
                hidden=false;
            }else{
                $(el_id).removeClass('openToggler');
                $(menu).removeClass('selected');
                hidden=true;
            }
        });
        $(el_id).mouseup(function() {
            return false;
        });
        $(document).mouseup(function(e){
        	if($(e.target).parent(el_id).length==0){
        		$(el_id).removeClass('openToggler');
        		$(menu).removeClass('selected');
        		hidden=true;
        	}
        });
    };
})( jQuery );
function msgSearchType(ee){
	$('#MessagingQuery').val($(ee).attr('role')+":");
	searchMessages();
}
function clickSearchBtn(ee){
	//$(ee).toggleClass('selected');
	//$(ee).parent('.wrap').toggleClass('openToggler');
	//$("#smsgbtn a" ).toggleButton('#smsgbtn');
}
function wallAPage(code, page){
	ajaxpoploading();
	var data = 'task=wall&status=ajaxpage&code='+code+'&page='+page;
	$.ajax({
		type: 'POST',
		url: '/ajax/main.php',
		data: data,
		success: function(response){
			$('#pagelet_stream_pager').remove();
			$('#home_stream').append(response);
			closepopup();
		}
	});
}
function fNewsAPage(page){
	ajaxpoploading();
	var data = 'task=home&status=ajaxpage&page='+page;
	$.ajax({
		type: 'POST',
		url: '/ajax/main.php',
		data: data,
		success: function(response){
			$('#pagelet_stream_pager').remove();
			$('#home_stream').append(response);
			closepopup();
		}
	});
}
function filesAPage(cat, page, search, lsf_id){
	ajaxpoploading();
	var data = 'task=files&status=ajaxpage&cat='+cat+'&page='+page+'&search='+search;
	$.ajax({
		type: 'POST',
		url: '/ajax/main.php',
		data: data,
		success: function(response){
			if(sf_id==lsf_id){
				$('#pagelet_stream_pager').remove();
				$('#results').append(response);
			}
			closepopup();
		}
	});
}
function newsAPage(page){
	ajaxpoploading();
	var data = 'task=news&status=ajaxpage&page='+page;
	$.ajax({
		type: 'POST',
		url: '/ajax/main.php',
		data: data,
		success: function(response){
			$('#pagelet_stream_pager').remove();
			$('#results').append(response);
			closepopup();
		}
	});
}
function contSellerActivation(){
	var url = $('#contSellerUrl').val();
	if(url!='' && url!=$('#contSellerUrl').attr('placeholder')){
		ajaxpoploading();
		var data = 'task=contentseller&status=activation&url='+url;
		$.ajax({
			type: 'POST',
			url: '/ajax/main.php',
			data: data,
			success: function(response){
				returnProcessJSON(response);
			}
		});
	}
}
function contentSellAPage(page){
	ajaxpoploading();
	var data = 'task=contentseller&status=ajaxpage&page='+page;
	$.ajax({
		type: 'POST',
		url: '/ajax/main.php',
		data: data,
		success: function(response){
			$('#pagelet_stream_pager').remove();
			$('#results').append(response);
			closepopup();
		}
	});
}
function msgAPage(code, page){
	ajaxpoploading();
	var data = 'task=message&status=ajaxPageDown&code='+code+'&page='+page;
	$.ajax({
		type: 'POST',
		url: '/ajax/main.php',
		data: data,
		success: function(response){
			//returnProcessJSON(response);
			$('#pagelet_stream_pager').remove();
			$('#allMsgs').append(response);
			closepopup();
		}
	});
}
function doOwnFile(code){
	ajaxpoploading();
	var data = 'task=files&status=doowndo&filecode='+code;
	$.ajax({
		type: 'POST',
		url: '/ajax/main.php',
		data: data,
		success: function(response){
			returnProcessJSON(response);
		}
	});
}
function showLikedPeople(fid, oid, section){
	ajaxpoploading();
	var data = 'task=like&status=likedpeople&fid='+fid+'&oid='+oid+'&section='+section;
	$.ajax({
		type: 'POST',
		url: '/ajax/main.php',
		data: data,
		success: function(response){
			returnProcessJSON(response);
		}
	});
}
function adjustObjHeight(obj, defaultHeight) {
    if(obj.scrollHeight > defaultHeight) {
        obj.style.height = obj.scrollHeight + 'px';
    } else {
        obj.style.height = defaultHeight + 'px';
    }
}
function comm_inputfocus(ee){
	$(ee).parents('.uiMentionsInput').addClass('uiTypeaheadFocused');
	$(ee).parents('ul .uiList').addClass('child_is_active child_is_focused');
	inputfocus(ee);
}
function comm_inputblur(ee){
	$(ee).parents('.uiMentionsInput').removeClass('uiTypeaheadFocused');
	inputblur(ee);
}
function show_all_comment(fid, oid, section){
	ajaxpoploading();
	var data = 'task=comment&fid='+fid+'&oid='+oid+'&section='+section;
	$.ajax({
		type: 'POST',
		url: '/ajax/main.php',
		data: data,
		success: function(response){
			returnProcessJSON(response);
		}
	});
}
function add_comment_text(event, me, fid, oid, section){
	if (event.keyCode == '13') {
		ajaxpoploading();
		comment = $(me).val();
		if(comment!=''){ $(me).val('');
			var data = 'task=comment&status=addcomment&fid='+fid+'&oid='+oid+'&section='+section+'&comment='+comment;
			$.ajax({
				type: 'POST',
				url: '/ajax/main.php',
				data: data,
				success: function(response){
					returnProcessJSON(response);
				}
			});
		}
	}
}
function show_like(fid, oid, section){
	ajaxpoploading();
	var data = 'task=like&status=showlike&fid='+fid+'&oid='+oid+'&section='+section;
	$.ajax({
		type: 'POST',
		url: '/ajax/main.php',
		data: data,
		success: function(response){
			returnProcessJSON(response);
		}
	});
}
function nc_like(fid, oid, section){
	ajaxpoploading();
	var data = 'task=like&fid='+fid+'&oid='+oid+'&section='+section;
	$.ajax({
		type: 'POST',
		url: '/ajax/main.php',
		data: data,
		success: function(response){
			returnProcessJSON(response);
			if($('#likeLink_'+fid+'_'+oid).html()=='Таалагдлаа'){
				$('#likeLink_'+fid+'_'+oid).html('Таалагдахаа болив');
				$('#like_'+fid+'_'+oid).removeClass('hidden_elem');
			}else{
				$('#likeLink_'+fid+'_'+oid).html('Таалагдлаа');
			}
		}
	});
	$('#likeLink_'+fid+'_'+oid).parents('.lkandcom').removeClass('collapsed_comments');
}
function nc_comment(ee){
	$(ee).parents('.lkandcom').removeClass('collapsed_comments');
}
function inputfocus(ee){
	if($(ee).val()==$(ee).attr('placeholder')){
		$(ee).val("");
	}
	$(ee).removeClass('DOMControl_placeholder');
}
function inputblur(ee){
	if($(ee).val()==""){
		$(ee).val($(ee).attr('placeholder'));
		$(ee).addClass('DOMControl_placeholder');
	}
}
function adPreview(){
	var title = "Гарчиг", body = "Энд таны сурталчилгааны текст байрлана.", url = '', ps;
	if($('#url').val()!=""){url = $('#url').val();}
	if($('#title').val()!=""){title = $('#title').val();}
	if($('#body').val()!=""){body = $('#body').val();}
	if($('#picture').val()!=""){picture = $('#picture').val(); ps = '<a href="'+url+'"><img class="img" src="/ads/'+picture+'" /></a>';}
	bs = '<a class="adLink" href="'+url+'">'+body+'</a>';
	ts = '<a class="adLink" href="'+url+'">'+title+'</a>';
	$('.adPreview .title').html(ts);
	$('.adPreview .image').html(ps);
	$('.adPreview .body').html(bs);
}
function limitChars(textarea, limit, infodiv){
	var text = textarea.value;
	var textlength = text.length;
	var info = document.getElementById(infodiv);
	if(textlength > limit){
		info.innerHTML = 'Та '+limit+'-аас илүү тэмдэгт бичиж болохгүй!';
		textarea.value = text.substr(0,limit);
		return false;
	}else{
		info.innerHTML = 'Та одоо '+ (limit - textlength) +' тэмдэгт бичих боломжтой.';
		return true;
	}
}
$('#login').keypress(function(event) {
	if (event.which == '13') {
		alert('Enter ...');
	}
});
function resetForm(id) {
	$('#'+id).each(function(){
	        this.reset();
	});
}
function submitForm(fname){
	ajaxpoploading();
	var data = $('#'+fname).serialize();
	$.ajax({
		type: 'POST',
		url: '/ajax/main.php',
		data: data,
		
		success: function(response){
			//$('.generic_dialog:last #pop_content').html(response);
			returnProcessJSON(response);
		}
	});
}
function sleep(milliSeconds){
	var startTime = new Date().getTime(); // get the current time
	while (new Date().getTime() < startTime + milliSeconds); // hog cpu
}
function returnProcessJSON(str){
	//alert(str);
	//str = '{"isLogin":true,"error":null,"errorSummary":null,"errorDescription":null,"css":null,"js":null}';
	var res = JSON.decode(str);
	//alert('JSON: '+res.htmlID);
	if(res.isLogin==true){
		if(res.js){
			for(var js in res.js){
				checkloadjscssfile(res.js[js], 'js');
			}
		}
		if(res.css){
			for(var css in res.css){
				checkloadjscssfile(res.css[css], 'css');
			}
		}
		if(res.htmlID){
			if(res.dialog==true){
				// ...
				if(res.overlay==true){
					$('#main').append('<div id="generic_dialog_overlay"></div>');
				}
				if(res.width!=0){
					//alert('alert: '+res.width);
					$('.generic_dialog:last .generic_dialog_popup').css('width', res.width);
				}
				$('.generic_dialog:last #pop_content').html(res.html);
			}else{
				$('#'+res.htmlID).html(res.html);
				closepopup();
			}
		}
		if(res.notice){
			notice(res.notice);
		}
		if(res.error){
			error_dialog(res.errorSummary, res.errorDescription);
		}
		if(res.returnLink){
			closepopup();
			if(res.returnLink.search('.php')>-1){
				window.location = res.returnLink;
			}else{
				window.location = '#'+res.returnLink;
				LMOnclick(res.returnLink, true);
			}
		}
	}else{
		error_dialog('Нэвтрэх', 'Уучлаарай таны холболт салсан байна та нэвтрэнэ үү');
	}
	eval(res.javascript);
	if(res.dialog==true){
		return false;
	}else{
		return res.column;
	}
}
function notice(body){
	str = '<div class="dialog_loading">'+body+'</div>';
	$('.generic_dialog:last #pop_content').fadeIn(1000).empty().append(str);
	setTimeout("closepopup()", 900);
	sleep(500);
}
function error_dialog(title, body){ 
	str = '<h2 class="dialog_title"><span>'+title+'</span></h2><div class="dialog_content"><div class="dialog_body"><div class="mbm pam uiBoxRed">'+body+'</div></div><div class="dialog_buttons clearfix"><a class="uiButton uiButtonDefault" onclick="closepopup();"><span class="uiButtonText">Хаах</span></a></div></div>';
	$('.generic_dialog:last #pop_content').fadeIn(1000).empty().append(str);
}
function ajaxpoploading(width){
	var offY = window.scrollY + 125;
	$('#main').children('.generic_dialog:last').css('display', 'none');
	strw = '';
	//if(width>0){
	//	strw = ' width: ' + width + 'px; ';
	//}
	//mydialog = '<div class="generic_dialog pop_dialog UIConnect_Dialog" style="display:block"><div class="generic_dialog_popup" style="top: ' + offY + 'px;"><div class="pop_container_advanced"><div id="pop_content" class="pop_content"><div class="dialog_loading">Ачааллаж байна...</div></div></div></div></div>';
	mydialog = '<div class="generic_dialog"><div class="generic_dialog_popup" style="top: ' + offY + 'px; ' + strw + '"><div class="pop_container_advanced"><div id="pop_content" class="pop_content"><div class="dialog_loading">Ачааллаж байна... <img src="/image/loading.gif" /></div></div></div></div></div>'
	$('#main').append(mydialog);
}
function closepopup(){
	over = $('#main').children('.generic_dialog:last').next();
	if(over){
		$(over).remove();
	}
	$('#main').children('.generic_dialog:last').remove();
	$('#main').children('.generic_dialog:last').css('display', 'block');
}
function LMOnclick(str, direct){
	var mstr = window.location.href;
	var elem = mstr.split('?');
	//alert(elem[0]);
	//alert('path: '+window.location.pathname);
	var str1 = "", sub = false, strAll = '';
	if(direct == true){
		sstr = "task=" + str;
		elem1 = str.split('&');
		str = elem1[0];
		if(elem1[1]){
			elem2 = elem1[1].split('=');
			if(elem2[0]=='status'){
				str1 = elem2[1];
				strAll = '';
			}else{
				str1 = '';
				strAll = '&'+elem1[1];
			}
		}else{
			strAll = '';
		}
	}else{
		sstr = elem[1];
	}
	if(window.location.pathname=='/home.php' || window.location.pathname=='/profile.php' ){
		if(str1!=''){
			$('#leftmenu').find('.subitem').each(function(){
				if($(this).attr('href')=='#'+str+'&status='+str1){
					root1 = $(this).parent();
					sub = true;
				}
			});
		}
		$('#leftmenu').find('a').each(function(){
			if($(this).attr('href')=='#'+str+strAll){
				root = $(this).parent();
			}
		});
		ajaxpoploading();
		if(sub){
			$(root1).addClass('loading');
			$.ajax({
				type: "POST",
				url: "/ajax/main.php",
				data: sstr,
				success: function(response){
					//$('#contentCol').html(response);
					col = returnProcessJSON(response);
					if(col!=false){
						if(col==2){$('#contentCol').addClass('hasRightCol');}else{$('#contentCol').removeClass('hasRightCol');}
					}
					$(root1).removeClass('loading');
					$('#leftmenu').find('li').each(function(){
				 		$(this).removeClass('selectedItem');
					});
					$(root1).addClass('selectedItem');
					$(root).addClass('open');
				}
			});
		}else{
			$(root).addClass('loading');
			$.ajax({
				type: "POST",
				url: "/ajax/main.php",
				data: sstr,
				success: function(response){
					//$('#contentCol').html(response);
					col = returnProcessJSON(response);
					if(col!=false){
						if(col==2){$('#contentCol').addClass('hasRightCol');}else{$('#contentCol').removeClass('hasRightCol');}
					}
					$(root).removeClass('loading');
					$('#leftmenu').find('li').each(function(){
				 		$(this).removeClass('selectedItem open');
					});
					$(root).addClass('selectedItem open');
				}
			});
		}
	}else{
		ajaxpoploading();
		$.ajax({
			type: "POST",
			url: "/ajax/main.php",
			data: sstr,
			success: function(response){
				//$('#contentCol').html(response);
				col = returnProcessJSON(response);
				if(col!=false){
					if(col==2){$('#contentCol').addClass('hasRightCol');}else{$('#contentCol').removeClass('hasRightCol');}
				}
			}
		});
	}
	
}
function ajaxrefresh(){
	var currURL = window.location.toString();
	var myparts = currURL.split("#");
	if(myparts.length == 2){
		LMOnclick(myparts[1], true);
	}else{
		window.location.reload();
	}
}
function ajaxwithback(surl){
	var currURL = window.location.toString();
	var myparts = currURL.split("#");
	if(myparts.length == 2){
		//document.write(myparts[1]);
		document.location = surl + "?task="+myparts[1];
	}
}
function loadjscssfile(filename, filetype, callback){
	 if (filetype=="js"){ //if filename is a external JavaScript file
	  var fileref=document.createElement('script')
	  fileref.setAttribute("type","text/javascript");
	  fileref.setAttribute("src", filename);
	 }
	 else if (filetype=="css"){ //if filename is an external CSS file
	  var fileref=document.createElement("link")
	  fileref.setAttribute("rel", "stylesheet");
	  fileref.setAttribute("type", "text/css");
	  fileref.setAttribute("href", filename);
	 }
	if(callback!=null){
	 	fileref.onload = function(){
			 callback();
		};
	}
	if (typeof fileref!="undefined")
		document.getElementsByTagName("head")[0].appendChild(fileref)
	}

	var filesadded=""; //list of files already added

function checkloadjscssfile(filename, filetype, callback){
	if (filesadded.indexOf("["+filename+"]")==-1){
		loadjscssfile(filename, filetype, callback);
		filesadded+="["+filename+"]"; //add to list of files already added, in the form of "[filename1],[filename2],etc"
	}else{
		if(callback!=null){
			callback();
		}
	}
}
function init(){
	loadjscssfile('/js/JSON.js', 'js');
	//$('head').append('<script type="text/javascript" src="http://www.file.mn/js/JSON.js"></script>');
	//$("body").append("<strong>Hello</strong>");
	//$('head').html('<script type="text/javascript" src="http://www.file.mn/js/JSON.js"></script>');
}
init();
