var serviceURL = 'inspect';   

if(!String.prototype.endsWith){
	String.prototype.endsWith = function(pattern) {
	    var d = this.length - pattern.length;
	    return d >= 0 && this.lastIndexOf(pattern) === d;
	};
}  
        
if(!String.prototype.trim){
    String.prototype.trim = function(){
        return this.replace(/^\s+/, '').replace(/\s+$/, '');    
    };
}
if(!String.prototype.startsWith){
	String.prototype.startsWith = function(pattern) {
	    return this.indexOf(pattern) === 0;
	};
}

function trimDim(dim){
	dim = ""+dim;
	if( dim && ( dim.endsWith('px') || dim.endsWith('pt'))){
		dim = dim.substring(0,dim.length-2);
	}
	return dim;
}

function randomString() {
	var chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 16;
	var randomstring = '';
	for (var i=string_length-1; i>=0; i--) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.charAt(rnum);
	}
	return randomstring;
}


function getBase(){
	var host = location.host;
	var port="";
	if(host.indexOf(":")==-1){
		// there is no port get it 
		port = location.port; 
		if(port==""){
		   return "http://"+host;
		}else{
		   return "http://"+host+":"+port;
		}
	}else{
	   return "http://"+host;
	}
}


var db ={
	explicit:{
		scale:1,
		oViewBoxString:null,
		width:null,
		height:null,
		oWidth:400,  // this value must be set to correct ones when svg is loaded 
		oHeight:300
	},
	implicit:{
		scale:1,
		oViewBoxString:null,
		width:null,
		height:null,
		oWidth:400,
		oHeight:300
	}
};


function getURLParams(key) {
    var result = [];
    var index = window.location.href.indexOf("?");
    if (index === -1) {
        return null;
    }
    var path = window.location.href.substr(index + 1);
    if (path.indexOf('#') > -1) {
        path = path.substr(0, path.indexOf('#'));
    }
    var params = path.split("&");
    for (var i = 0; i < params.length; i++) {
        var pair = params[i];
        var index = pair.indexOf('=');
        if (index === -1 || key != pair.substr(0, index)){ continue;}
        var value = params[i].substr(index + 1);
        result.push(decodeURIComponent(value.replace(/\+/g, ' ')));
    }
    return result;
}

function getURLParam(key) {
    var params = getURLParams(key);
    if (params===null || params.length === 0) {
        return null;
    }
    return params[0];
}

        
if(!String.prototype.trim){
    String.prototype.trim = function(){
        return this.replace(/^\s+/, '').replace(/\s+$/, '');    
    };
}

if(!Array.prototype.unique){
    Array.prototype.unique = function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        // If this[i] is found later in the array
        if (this[i] === this[j])
          j = ++i;
      }
      a.push(this[i]);
    }
    return a;
  };
}

function unescapeEscapedNonASCII(str){
	var a = str.match(/(\\u[A-Fa-f0-9]{4})+/g);
	if(a!=null){
		for(var i=0;i<a.length;i++){
		    str = str.replace(a[i],unescapeFromUtf16(a[i]));
		}
	}
	return str;
}

function escapeNonASCII(str){
	var retStr = '';
	for(var i=0;i<str.length;i++){
		var c = codePointAt(str, i)
	    if(!/[A-Za-z0-9\s]/.test(c)){
			//console.log("detected non ascii char ["+c+"]")
			retStr += escapeToUtf16(c);
				
			// check for lower surrogate, if detected increase index to not get the same character twice 
			var c = str.charAt(i);
			var code = c.charCodeAt(0);
			if (code >= 0xD800 && code <= 0xDBFF) { 
		        // lower surrogate detected, we need to fetch more char
				i++;
			}
	    }else{
			retStr += c;
	    }
	}
	return retStr;
}

function codePointAt(s, pos) {
    var c = s.charAt(pos);
    if (c == "") {
        return c;
    }
    var code = c.charCodeAt(0);
    if (code >= 0xD800 && code <= 0xDBFF) { 
        // lower surrogate detected, we need to fetch more char
        if (pos < s.length - 1) {
            code = s.charCodeAt(pos + 1);
            var ret = code < 0xDC00 || code > 0xDFFF ? "" : s.substring(pos, pos + 2); 
            return ret;
        } else {
            return ""; // error in the string
        }
    } else if (code >= 0xDC00 && code <= 0xDFFF) {
        // higher surrogate detected, we need to fetch more char backward
    	if (pos > 0) {
            code = s.charCodeAt(pos - 1);
            var ret = code < 0xD800 || code > 0xDBFF ? "" : s.substring(pos - 1, pos + 1);
            return ret
        } else {
            return ""; // error in the string
        }
    } else{
    	return s.charAt(pos);
    }
}


function constructNTriple(triple){
	var str =[];
		str.push(construct(triple,"s"));
		str.push(construct(triple,"p"));
		str.push(construct(triple,"o"));
	return str.join("");  
}

function construct(triple,spo){
	var type = triple[spo].type;
	var value = triple[spo].value.trim(); 
		
	var str =[];
	if(type==="uri"){
		str.push("<");
		str.push(value);
		str.push("> ");	
	}else if(type==="bnode"){
		//str.push("_:");
		str.push(value);
		str.push(" ");
	}else if(type==="literal"){
		value = escapeNonASCII(value);
		str.push('"');
		str.push( value.replace(/\\/g,'\\').replace(/"/g,'\\"')  );
		str.push('" ');   //TODO here also other character then " should be escaped
	}else{
		str.push(value);
		str.push(' '); 
	}
	if(spo=="o"){
		str.push(".\n");
	}
	
	return str.join("");	
}

function replaceSpecialCharactersByEntities(s){
	return s.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");
}

function printTripleValue(triple,spo){
	var value = triple[spo].value.trim();
	var type =triple[spo].type;
	var valueString = value;
	
	if(type==='uri'){
	    titleValueString = valueString;
	    var replaced = SindiceInspector.replacePrefix(valueString);
	    if(replaced===valueString){
		    replaced = replaceSpecialCharactersByEntities(replaced);
	    	return '<td class="wordWrap"><a href="'+value+'" title="'+titleValueString+'" target="_blank">&lt;'+replaced+'&gt;</a></td>';
	    }else{
		    replaced = replaceSpecialCharactersByEntities(replaced);
		    return '<td class="wordWrap"><a href="'+value+'" title="'+titleValueString+'" target="_blank">'+replaced+'</a></td>';
	    }
	    valueString = replaceSpecialCharactersByEntities(valueString); 
    }else if(type==="bnode"){
	    valueString = replaceSpecialCharactersByEntities(valueString); 
    	return '<td class="wordWrap"><span title="'+valueString+'">'+valueString+'</span></td>';
	}else if(type==='literal'){
	    valueString = replaceSpecialCharactersByEntities(valueString); 
		return '<td class="wordWrap"><span title="'+valueString+'">'+valueString+'</span></td>';
    }else{
	    valueString = replaceSpecialCharactersByEntities(valueString); 
    	return '<td class="wordWrap"><span>'+valueString + "[type:"+type+"]</span></td>";
    }
}

