var showOkkam=false;
function printMessageWindow(selector,msg,msgType){
	var icon ="ui-icon-alert";
	var state ="ui-state-highlight";
	var issueType="Warning";
	if(msgType=="error"){
		icon ="ui-icon-circle-close";
		state ="ui-state-error";
		issueType="Error";
	}
	
	var html=[];
	html.push('
');
	jQuery(selector).empty().append(html.join('')).show();
}
function getHtml(xmlString,selector){
   jQuery.ajax({
	   type: "POST",
	   url: "proxy/redefer/rdf2html?"+randomString(),
	   cache:false,
	   dataType:"text",
	   data:{
            rdf:xmlString,
	   		mode:"snippet",
	   		namespaces:false,
	   		language:"en"
	   },
	   contentType:"application/x-www-form-urlencoded",
	   success: function(data){
			jQuery("#tabs-HTML div."+selector).html(data);
			jQuery("img[src='http://rhizomik.net/images/rhizomer.small.png']").attr('src','img/rhizomer.small.png');
	   },
	   error:function (XMLHttpRequest, textStatus, errorThrown){
        	var msg = "ajax error function getHtml ["+XMLHttpRequest.status+"] ["+textStatus+"] ["+ errorThrown+"]";
        	printMessageWindow("#tabs-HTML div.msg",msg,"error");
       }
	   
   });
}
function getSvg(xmlString,selector){
	jQuery.ajax({
	   type: "POST",
	   url: "proxy/redefer/render?"+randomString(),
	   cache:false,
	   dataType:"xml",
	   data:{
        rdf:xmlString,
        rules:"http://inspector.sindice.com/proxy/redefer/rules/showgraph.jrule",
		format:"RDF/XML",
		mode:'snippet'
	   },
	   contentType:"application/x-www-form-urlencoded",
	   success: function(svgData){
			var embedSvgElement = svgData.getElementsByTagName( 'svg' )[0]; 
			var clonedNode = embedSvgElement.cloneNode(true); 
			//get the main SVG element 
			
			jQuery("#svg"+selector).html('');
			
			var mainSvgElement = document.getElementById ( 'svg'+selector+'_x' ); 
			//append embed SVG to main SVG 
			mainSvgElement.appendChild ( clonedNode ); 
			if(selector.indexOf("explicit")!=-1 ){
				jQuery("#graph1 polygon:first",jQuery("div.rhizonik_svg.explicit")).css({"fill":"none",stroke:"none"});
				
                var svgHeight = jQuery("div.rhizonik_svg.explicit svg").get(0).height.baseVal.value;
                var svgWidth = jQuery("div.rhizonik_svg.explicit svg").get(0).width.baseVal.value;
                
	            db.explicit.oWidth = svgWidth;	
	            db.explicit.oHeight = svgHeight;	
				addSlider("explicit");
                SindiceInspector.addNamespacesLegend("#svgexplicit",xmlString);
            }
         if(selector.indexOf("implicit")!=-1 ){
				jQuery("#graph1 polygon:first",jQuery("div.rhizonik_svg.implicit")).css({"fill":"none",stroke:"none"});
                var svgHeight = jQuery("div.rhizonik_svg.implicit svg").get(0).height.baseVal.value;
                var svgWidth = jQuery("div.rhizonik_svg.implicit svg").get(0).width.baseVal.value;
	            db.implicit.oWidth = svgWidth;	
	            db.implicit.oHeight = svgHeight;	
                addSlider("implicit");
                SindiceInspector.addNamespacesLegend("#svgimplicit",xmlString);
            }
            svgLoadedFlag=true;
            
	   },
	   error:function (XMLHttpRequest, textStatus, errorThrown){
        	var msg = "ajax error function getSvg ["+XMLHttpRequest.status+"] ["+textStatus+"] ["+ errorThrown+"]";
        	printMessageWindow("#tabs-GRAPH div.msg",msg,"error");
       }
  });
}
function XML2String(elem){
	var serialized;
	try {
		// XMLSerializer exists in current Mozilla browsers
		serializer = new XMLSerializer();
		serialized = serializer.serializeToString(elem);
	} 
	catch (e) {
		// Internet Explorer has a different approach to serializing XML
		serialized = elem.xml;
	}
	
	return serialized;
}
function initSigma(url){
	var sigmaUrl = "http://sig.ma/";
	if(url){
		if(jQuery("#tabs-SIGMA object").size()!=0){
			jQuery("#tabs-SIGMA object").attr("data",sigmaUrl+"search?raw=1&q=&singlesource="+encodeURIComponent(url));
		}else{
			jQuery("#tabs-SIGMA iframe").attr("src",sigmaUrl+"search?raw=1&q=&singlesource="+encodeURIComponent(url));
		}
	}else{
		//TODO: cant make sigma no keyword no url 
	}
}
function cleanInspectionLog(){
	jQuery("#inspectionLog").empty();
}
		
function updateStatus(){
	jQuery("#inspectionProgressbar").progressbar();
	jQuery.ajax({
	  type: "GET",
     url: serviceURL,
     cache:false,
     dataType: 'json',
     data: {
         action:"getStatus",
         format:"json"
     },
     error: function(){
     },
     success: function(json){
     		var status = json.status;
     		var progress = json.progress;
     		var statusMsg = json.statusMsg;
     		var count = json.count;
     		var id = json.id;
     		
     		jQuery("#inspectionProgressbar").progressbar( "option", "value",progress);
     		if(progress>=0 && progress <100){
     			jQuery("#inspectionProgressbar").show();
     		}else{
     			jQuery("#inspectionProgressbar").hide();
     		}
     		var html = "";
     		var error = false;
     		for(var i=0;i'+o.m+'
';
     			}else{
     				html+=''+o.m+'
';
     			}
     		}
     		
     		jQuery("#inspectionLog").html(html);
     		if(status!="done"){
     			setTimeout(updateStatus,1000);
     		}else if(!error){
     			// hide only if no errors !!!
     			hideDialog();
     		}
     }	
	});
}
function hideDialog(){
	jQuery('#dialog div.loader').hide();
	
	var t = jQuery("#openDialog").offset().top+10;
	var l = jQuery("#openDialog").offset().left+10;
	
	jQuery(".ui-dialog").animate({
		width: 0,
		height: 0,
		left:l,
		top:t,
		opacity: 0.4,
	},1000,function(){
		jQuery('#dialog').dialog('close');
	});
}
function testCookie(){
	var n = "wedspector-test";
	createCookie(n,n,1);
	var res = readCookie(n)==n?true:false;     	
	eraseCookie(n);
	return res;
}
function isTextNode(){
	// If this is a text node, return true.
	return( this.nodeType === 3 );
}
function runRDFExtractor(parameters){
		cleanInspectionLog();
		cleanPreviousResults();
		jQuery('#dialog div.loader').show();
     	jQuery('#dialog').dialog('open');
     	// check that cookies are enabled
     	if(testCookie()){
	     	setTimeout(updateStatus,10);
     	}else{
     		jQuery("#inspectionLog").val("Inspection log needs cookies in order to operate.\n" +
     											  "It seems cookies are disabled in your browser.\n"+
     											  "Please enable cookies to use Inspection log.\n");
     	}
		
		if(parameters.url=="" && parameters.content==""){
			alert("Uri and Content were empty. Please provide at least one of these two.");
			document.location.href = "/inspector";
			return;
		}
		
		//console.log(parameters);
		jQuery("#inspector-results").show();
	
		ontologies = {};
		destroyOntologyTree();
		
		jQuery("#RDFExtractorResults tbody").html('');
		//jQuery('#indicator').attr("src","img/ajax-loader.gif");
		
		jQuery.ajax(
		        {
		        type: "POST",
		        url: serviceURL,
		        dataType: 'json',
		        traditional:true,
		        data:parameters,
		        error: function(){
		        	//jQuery('#indicator').attr("src","img/ajax-blank-loader.gif");
		            //TODO: display error message in progress report window
		            //alert("Server error ");
		        },
		        success: function(json){
		        	//jQuery('#indicator').attr("src","img/ajax-blank-loader.gif");
		        	if(json.status==="error"){
		                alert( "error: " + json.error +"\n" +json.errorDetail );
		            }else if(json.status==="ok"){
		            	jQuery("#tabs-ORIGINAL-CONTENT textarea.requestHeaders").text(json.rawContentRequestHeaders);
                        jQuery("#tabs-ORIGINAL-CONTENT textarea.headers").text(json.rawContentHeaders);
                        jQuery("#tabs-ORIGINAL-CONTENT textarea.content").text(json.rawContent);
                    var usedExtractors = '';
                    jQuery(".usedExtractors").html(usedExtractors);
		            	
		            	jQuery('#RDFExtractor textarea').animate({ height:"24px" } , 200 );
		            	var a=[];b=0;
		                var nTStrExplicit=[];
		                var nTStrImplicit=[];
		                var explicit =json.extractorResults.metadata.explicit;
		                var explicitNo = explicit.bindings.length;
		                var explicitLeft = explicit.left;
		                
		                var implicitNo =0,implicitLeft=0;
		                for(var i=0;i';
					            a[b++]= printTripleValue(triple,'s');
					            a[b++]= printTripleValue(triple,'p');
					            a[b++]= printTripleValue(triple,'o');
					            a[b++]='';
		                    	nTStrExplicit.push(constructNTriple(triple)); 
		                }
	
		                if(parameters.doReasoning && json.extractorResults.metadata.inferred){
		                	var implicit = json.extractorResults.metadata.inferred;
		                	implicitNo = implicit.bindings.length;
		                	implicitLeft = implicit.left;
		                	
		                	for(var i=0;i';
		                        a[b++]= printTripleValue(triple,'s');
		                        a[b++]= printTripleValue(triple,'p');
		                        a[b++]= printTripleValue(triple,'o');
		                        a[b++]='';
		                    
		                    	nTStrImplicit.push(constructNTriple(triple));
		                    }
		                }
		                
		                nTStrExplicitS = nTStrExplicit.join("");
		                nTStrImplicitS = nTStrImplicit.join("");  
		                
		                jQuery("#RDFExtractorResults").append(a.join(''));
		                
		                // dataTables
						jQuery("table.display").dataTable({
							"iDisplayLength": -1,
							"bAutoWidth":true,
							"bDestroy": true,
							"aLengthMenu": [[100, 250, 500, -1], [100, 250, 500, "All"]],
							//"bJQueryUI": true,
							//"sDom": '<"H"lfr>t<"F"ip>'
							"sDom": '"H"ft',
							"fnInitComplete": function(oSettings, json) {
								// here call this because after choosing custom extractors and hit refresh 
								// table width was for some reason set to 100px
								jQuery("table.display").css({width:"100%"});
					        }
						});
						
						var textNode = jQuery(".dataTables_filter label" ).contents().filter( isTextNode );
						textNode.last().replaceWith(document.createTextNode( "Filter: " ));
						
		                printTriplesWarningIfNotAllPrinted(explicitNo,implicitNo,explicitLeft,implicitLeft);
		                printTriplesInfo(explicitNo,implicitNo,explicitLeft,implicitLeft);
		                
		                if(explicitNo==0){	
		                	printMessageWindow("#tabs-TRIPLES div.msg","No triples have been found in the document","warning");
		                }else{
		                	showTriplesTab();
                        printNTriples("explicit",nTStrExplicitS);
                        var xmlString = json.extractorResults.metadata.explicit.bindingsRDFXML;
                        getSvg( xmlString,"explicit");
                        getHtml(xmlString,"explicit");
                        //SindiceInspector.addNamespacesLegend("#ntriples pre.explicit",xmlString);
                        jQuery("#rdfxml pre.explicit").text(xmlString);
                        }
                        if(parameters.doReasoning && implicitNo>0){
	                        printNTriples("implicit",nTStrImplicitS);
	                        xmlString = json.extractorResults.metadata.inferred.bindingsRDFXML;
	                        getSvg( xmlString,"implicit");
	                        getHtml(xmlString,"implicit");
	                        //SindiceInspector.addNamespacesLegend("#ntriples pre.implicit",xmlString);
                            jQuery("#rdfxml pre.implicit").text(xmlString);
			            }
		                
		                // these two making preblems when page is served as xhtml
		                if(explicitNo==0){
		                	printMessageWindow("#tabs-ONTOLOGIES div.msg","No ontologies have been found in the document","warning");
		                	printMessageWindow("#tabs-GRAPH div.msg","No triples have been found in the document","warning");
		                	printMessageWindow("#tabs-HTML div.msg","No triples have been found in the document","warning");
		                	printMessageWindow("#tabs-SIGMA div.msg","No triples have been found in the document","warning");
		                	jQuery("#tabs-SIGMA iframe").hide();
		                }else{	 
			               showOntologiesTab();
		                	if(parameters.doReasoning && json.extractorResults.metadata.ontologies){
			                	jsonTreeData = buildJsonTreeData(parameters.url,json.extractorResults.metadata.ontologies)
				            	initOntologyTree(parameters.url);
				            	ontologyList = getOntologiesList(parameters.url,json.extractorResults.metadata.ontologies);
				            	printOntologyList(ontologyList);
			            	}else{
			            		
			            		printOntologyLink(parameters); // takes parameters from global scope
			            	}
		                }
		            	// here dispaly the validation result
		            	jQuery(".validation-results").empty();
		            	
		            	
		            	if(parameters.doTriplesValidation=="1" || parameters.doSyntaxValidation=="1"){
			            	jQuery("a[href='#tabs-VALIDATION']").parent().show();
			            	jQuery("#tabs-VALIDATION").show();
			            	
			            	if(showOkkam===true){
			            		showOkkamDemoTab(json.extractorResults.metadata.explicit.bindings);
			            	}
			               if(json.contentType=="application/rdf+xml"){
			            			printW3cRdfValidationResult(json.w3cRdfValidationRes);
				            		selectValidationTab("#tabs-RDF-SYNTAX-VALIDATION");
			            	}else if(json.contentType.indexOf("html")!=-1){
				        			printW3cMarkupValidationResult(json.w3cMarkupValidationRes);
				            		printCommonMistakesValidationResult(json.commonMistakesValidationRes);
				            		selectValidationTab("#tabs-SYNTAX-VALIDATION");
					        }
		            	
			            	if(json.rdfValidationRes && json.rdfValidationRes.results &&json.rdfValidationRes.results){
			            		printRdfValidationResult(json.rdfValidationRes);
			            		selectValidationTab("#tabs-PEDANTIC-VALIDATION");
			            	}
			          	//make first validation tab active
			          	
			          }
		            	
		            	
		            	jQuery(".ajaxLoader").hide();
		            	return false;
		            }
		        }
		    }   
		);
		return false;
}
function showTriplesTab(){
	jQuery("#tabs-TRIPLES div.legendBox").show();
	jQuery("#tabs-TRIPLES div#sortableTriples").show();
}
function showOntologiesTab(){
	jQuery("#tabs-ONTOLOGIES div.ontologiesBox").show();
}
function printTriplesWarningIfNotAllPrinted(explicitNo,implicitNo,explicitLeft,implicitLeft){
	var msg ="";
	if(explicitLeft>0){
		msg += formatMsgABoutToManyTriples("explicit",explicitNo,explicitLeft);
	}
	if(implicitLeft>0){
		msg += formatMsgABoutToManyTriples("inferred",implicitNo,implicitLeft);
	}
	if(explicitLeft>0 || implicitLeft>0){
		
		printMessageWindow("#tabs-GRAPH div.msg",msg,"warning");
		printMessageWindow("#tabs-HTML div.msg",msg,"warning");
		printMessageWindow("#tabs-TRIPLES div.msg",msg,"warning");
	}
}
function formatMsgABoutToManyTriples(name,printedNo,leftNo){
	return "The total number of "+name+" triples is "+(printedNo+leftNo)+" Sorry but due to usability reasons only first "+printedNo+" were printed.";
}
function printTriplesInfo(explicitNo,implicitNo,explicitLeft,implicitLeft){
	var infoStr = "Triples "+(explicitNo+explicitLeft)+' expl./'+(implicitNo+implicitLeft)+' impl.';
	jQuery("#triplesTab").html(infoStr);
	jQuery("#explicitNo").text(explicitNo+explicitLeft);
	jQuery("#implicitNo").text(implicitNo+implicitLeft);
}
function printNTriples(selector,triplesStr){
	jQuery("#ntriples pre."+selector).text(triplesStr);
}
function cleanPreviousResults(){
	printTriplesInfo(0,0,0,0);
	jQuery("#ntriples pre").empty();
	jQuery("#rdfxml pre").empty();
	jQuery("div.result").empty();
	jQuery("#svgexplicit").empty();
	jQuery("#svgimplicit").empty();
	jQuery("#tabs-TRIPLES div.explicit").empty();
	jQuery("#tabs-TRIPLES div.implicit").empty();
	jQuery("#tabs-TRIPLES .msg").hide();
    jQuery("#tabs-ONTOLOGIES .msg").hide();
    jQuery("#tabs-SIGMA .msg").hide();
    jQuery("#tabs-GRAPH .msg").hide();
    jQuery("#tabs-HTML .msg").hide();
}
var TABS;
var VALIDATION_TABS;
jQuery(document).ready(function(){
	var sigmaLoaded = false;
    
	jQuery(".useExtractors").live('click',function(){
		sigmaLoaded=false;
		jQuery("#tabs-SIGMA iframe").show();
		parameters.useExtractors= jQuery('.useExtractorsList').val();
		runRDFExtractor(parameters);
	});
	
	jQuery('#openDialog').click(function(){
		jQuery('#dialog').dialog('open');
	});
	jQuery("#dialog").dialog({
		autoOpen: false,
		modal: true,
		width:500,
		open:function(event, ui){
			jQuery(".ui-dialog").css({'opacity':1,"margin-top":"4px"});
		}
	});
	
	
	
	jQuery("#openDialog").button({
      icons: {
          primary: 'ui-icon-clock'
      }
	});
	
	jQuery("#refresh").button({
      icons: {
          primary: 'ui-icon-refresh'
      }
	}).click(function(){
		location.reload(true);
	});
	
	jQuery("#newInspection").button({
      icons: {
          primary: 'ui-icon-home'
      }
	});
	
	
	VALIDATION_TABS = jQuery("#tabs3").tabs({
		select: function(event, ui) {
			document.location.hash =  jQuery(ui.panel).attr("id").slice(5);
		}
	}); 
		
	TABS = jQuery("#tabs").tabs({
		select: function(event, ui) {
			if(!sigmaLoaded && ui.panel.id=="tabs-SIGMA"){
				//init sigma when user clicks on sigma tab was selected
				initSigma(parameters.url);
				sigmaLoaded=true;
			}
	        document.location.hash =  jQuery(ui.panel).attr("id").slice(5);
		 }
	});
	
	var hash = document.location.hash.slice(1);
	if(hash=="SIGMA"){
		TABS.tabs('select', "#tabs-"+hash); 
		initSigma(parameters.url);
		sigmaLoaded=true;
	}else if(hash==""){
		TABS.tabs('select', "#tabs-TRIPLES"); 
	}else if(hash=="COMMON-MISTAKES-VALIDATION" || 
			 hash=="SYNTAX-VALIDATION" || 
			 hash=="RDF-SYNTAX-VALIDATION" ||
			 hash=="PEDANTIC-VALIDATION" ||
			 hash=="OKKAM-VALIDATION"){
		VALIDATION_TABS.tabs('select', "#tabs-"+hash); 
	}else{
		TABS.tabs('select', "#tabs-"+hash); 
	}
	
	runRDFExtractor(parameters);
	if(getURLParam('raw') == '1'){
        jQuery('div#RDFExtractor').addClass('raw');
    }   
    jQuery('#RDFExtractorContent').click(function(){
    	var H = 200;
    	if(jQuery(this).height()!=H){
    		jQuery(this).animate({ height:"200px" } ,"fast" );
    	}else{
    		//jQuery(this).animate({ height:"48px" } ,"fast" );
    	}
   	});
   
    jQuery('#RDFExtractorShowExplicit').click(function(){
    	if(jQuery('#RDFExtractorShowExplicit:checked').size()){
        	jQuery(".explicit").show();
    	}else{
        	jQuery(".explicit").hide();
    	}
    });
    
    jQuery('#RDFExtractorShowImplicit').click(function(){
    	if(jQuery('#RDFExtractorShowImplicit:checked').size()){
        	jQuery(".implicit").show();
    	}else{
        	jQuery(".implicit").hide();
    	}
    });
    
	jQuery("#serializedGraphFormat").change(function(){
		var id = jQuery(this).val();
		jQuery(".serializedGraphContainer").hide();
		jQuery("#"+id).show();
	});
	
	prettyPrint();
});