(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);
$(document).ready(function() {
    $('#askquestion').click(function() {
    	if ($('#adminmsg').length == 0) {
    		$('span.spnmiddle').css('display','block');
    		$.blockUI({ message: $('#msgwin'), draggable: true,css: { top: '10%',width:'45%',left:'30%',cursor:'default','-moz-border-radius': '10px'}});
    		return;
    	}
    	$.ajax({url: projectPath+'/urlservlet.do?block=blocked&dateinfo='+new Date().getTime(),
            success: function(data) {
    		     data = eval('['+data+']')[0];
    		     $('#base').css('display','none');
    	    	 $('#msgdiv').css('display','none')
        	     if (data.block == 'true') {
        	    	 $('#adminmsg').html(decodeURIComponent(String(data.msg).replace(/%0A/g, '<br />').replace(/\+/g,' ')));
        	    	 $('#msgdiv').css('display','block')
        	    	 $('span.spnleft').css('display','none');
        	    	 $('span.spnright').css('display','none');
        	    	 $('span.spnmiddle').css('display','block');
        	     } else {
        	    	 $('#base').css('display','block');
        	    	 $('span.spnleft').css('display','block');
        	    	 $('span.spnright').css('display','block');
        	    	 $('span.spnmiddle').css('display','none');
        	     }
            },
            failure:function() {
            }
    	});
        $.blockUI({ 
            message: $('#msgwin'), 
			draggable: true,
            css: { top: '10%',width:'45%',left:'30%',cursor:'default','-moz-border-radius': '10px'}
        });
    });
    $('span.spnmiddle').click(function() {$.unblockUI();})
    $('span.spnleft').click(function() {$.unblockUI();})
    $('span.spnright').click(function() {$.unblockUI({
    	onUnblock: function(){window.location=projectPath+"/showuserview.do?function=questionSubmit";} 
    });})
    
    $(".signin").click(function(e) {          
		e.preventDefault();
        $("fieldset#signin_menu").toggle();
		$(".signin").toggleClass("menu-open");
		$('#signin')[0].reset();
		$('#error').css('display','none');
		$('#error').html('');
		$('#username-lab').css('color','#789');
		$('#password-lab').css('color','#789');
    });
	
	$("fieldset#signin_menu").mouseup(function() {return false});
	$(document).mouseup(function(e) {
		if($(e.target).parent("a.signin").length==0) {
			$(".signin").removeClass("menu-open");
			$("fieldset#signin_menu").hide();
		}
	});
	
	$('#username , #password').keypress(function(e) {
		var evt=(e)?e:(window.event)?window.event:null;
		if(evt){
			var key=(evt.charCode)?evt.charCode:((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));		
			if(key=="13") {makeLogin();return false;}
		}
		return true;
	});
	
	function megaHoverOver(){
		$(this).find(".sub").stop().fadeTo('fast', 1).show();
		//Calculate width of all ul's
		(function($) { 
			jQuery.fn.calcSubWidth = function() {
				rowWidth = 0;
				//Calculate row
				$(this).find("ul").each(function() {					
					rowWidth += $(this).width(); 
				});	
			};
		})(jQuery); 
		
		if ( $(this).find(".row").length > 0 ) { //If row exists...
			var biggestRow = 0;	
			//Calculate each row
			$(this).find(".row").each(function() {							   
				$(this).calcSubWidth();
				//Find biggest row
				if(rowWidth > biggestRow) {
					biggestRow = rowWidth;
				}
			});
			//Set width
			$(this).find(".sub").css({'width' :biggestRow});
			$(this).find(".row:last").css({'margin':'0'});
			
		} else { //If row does not exist...
			
			$(this).calcSubWidth();
			//Set Width
			$(this).find(".sub").css({'width' : rowWidth});
			
		}
	}
	
	function megaHoverOut(){ 
	  $(this).find(".sub").stop().fadeTo('fast', 0, function() {
		  $(this).hide(); 
	  });
	}
 
 
	var config = {    
		 sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
		 interval: 100, // number = milliseconds for onMouseOver polling interval    
		 over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
		 timeout: 500, // number = milliseconds delay before onMouseOut    
		 out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
	};
 
	$("ul#topnav li .sub").css({'opacity':'0'});
	$("ul#topnav li").hoverIntent(config);
	
	$("ul#topnav_urdu li .sub").css({'opacity':'0'});
	$("ul#topnav_urdu li").hoverIntent(config);
	if ($('#allnews').length == 0) return;
	var newslist = {'1': [],'2': [], '3': [], '4': []};
	$.ajax({
		url:'pdfupload.do',type:'post',data:{newsoption:'load'},dataType:'json',success:function(res) {
			var arr = res.Rows,res = []; 
			if (arr.length == 0) return;
			$.each(arr,function(key,val) {
				//res.push('<li><a href="pdfupload.do?filename='+val.pdf_filename+'&newsoption=download">'+val.news_detail+'</a>');
				newslist[val.news_type].push('<li><a href="pdfupload.do?filename='+val.pdf_filename+'&newsoption=download">'+val.news_detail+'</a>');
			});
			
			$('#urdu_news ul').html(decodeURIComponent(newslist['1'].join('')));
			$('#urdu_article ul').html(decodeURIComponent(newslist['2'].join('')));
			$('#english_news ul').html(decodeURIComponent(newslist['3'].join('')));
			$('#english_article ul').html(decodeURIComponent(newslist['4'].join('')));
			/*$('#newscontent').html(res.join(''));
			$('#News').animate({
			    width: ['toggle', 'swing'],
			    height: ['toggle', 'swing'],
			    opacity: 'toggle'
			});
			$('span.x-tool').click(function() {
				$("#News").slideUp("fast");
			})*/
		}
	});
}); 

var SEARCH_LIMIT = 10;
function overmouse(ref) {ref.style.backgroundColor = '#99CC00';}
function outmouse(ref) {ref.style.backgroundColor = '#FFFFFF';}
function viewquestion(type, subtype,lan) {
	document.submitform.query.value=encodeURIComponent('<c>'+type+'</c><s>'+subtype+'</s><l>'+lan+'</l>');
    document.submitform.limit.value = SEARCH_LIMIT; 
    document.submitform.passquery.value = lan;
    document.submitform.submit();
}

function makeErr(opt) {
	var ss = $('#signin_menu');
	ss.find(':input').each(function() {
		var s = $('#'+$(this).attr('id')+'-lab');
		if (opt == 'err') {if (s && $.trim($(this).val()) == '') s.css('color','red');}
		else if (opt == 'all') {if (s) s.css('color','red');}
		else if (opt == 'none') {if (s) s.css('color','#789');}
	});
}

function makeLogin() {
	$('#error').css('display','none');
	$('#ajax').css('display','inline');
	makeErr('none'); 
	questionform.makLogin(document.getElementById("username").value, document.getElementById("password").value,{
		callback:function(str) {
		    if (str == 'fill') {
		    	$('#ajax').css('display','none');
		    	makeErr('err');
		    	$('#error').html('All field are required');
		    	//$('#error').html('<span>Invalid username or password</span>');
		    	$('#error').css('display','inline');
		    } else if (str == 'invalid') {
		    	$('#ajax').css('display','none');
		    	makeErr('all');
		    	$('#error').html('<span>Invalid username or <br />password</span>');
		    	$('#error').css('display','inline');
		    } else if (str == 'success') {
		    	window.location = 'showuserview.do?function=menu&all=all&forward=userpage'
		    }
		},
		failure:function(message) {
			alert(message);
		}
	});
}
function querySt(ji) {
    var hu = window.location.search.substring(1);
	var gy = hu.split("&");
	for (var i=0, node; node = gy[i++];) {
		var ft = node.split("=");
		if (ft[0] == ji) return ft[1];
	}
	return "";
}
function loadprev() {
	var idx = querySt('idxpg');
	if (idx == '1') {
		window.location = 'showuserview.do?function=menu&all=all&forward=userpage&limit='+(parseInt(querySt('limit')) - 1);
		return;
	}
		var frm = document.submitform;
		frm.action += '&limit='+(parseInt(querySt('limit')) - 1);
		frm.query.value=encodeURIComponent(decodeURIComponent(querySt('qry')));
	    frm.limit.value = SEARCH_LIMIT; 
	    frm.passquery.value = querySt('all');
	    frm.submit();
	
}
