/*
 * proxy patch
 */
Ext.lib.Ajax.isCrossDomain = function(u) {
	var match = /(?:(\w*:)\/\/)?([\w\.]*(?::\d*)?)/.exec(u);
	if (!match[1]) return false; // No protocol, not cross-domain
	return (match[1] != location.protocol) || (match[2] != location.host);
};

Ext.override(Ext.data.Connection, {

    request : function(o){
        if(this.fireEvent("beforerequest", this, o) !== false){
            var p = o.params;

            if(typeof p == "function"){
                p = p.call(o.scope||window, o);
            }
            if(typeof p == "object"){
                p = Ext.urlEncode(p);
            }
            if(this.extraParams){
                var extras = Ext.urlEncode(this.extraParams);
                p = p ? (p + '&' + extras) : extras;
            }

            var url = o.url || this.url;
            if(typeof url == 'function'){
                url = url.call(o.scope||window, o);
            }

            if(o.form){
                var form = Ext.getDom(o.form);
                url = url || form.action;

                var enctype = form.getAttribute("enctype");
                if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
                    return this.doFormUpload(o, p, url);
                }
                var f = Ext.lib.Ajax.serializeForm(form);
                p = p ? (p + '&' + f) : f;
            }

            var hs = o.headers;
            if(this.defaultHeaders){
                hs = Ext.apply(hs || {}, this.defaultHeaders);
                if(!o.headers){
                    o.headers = hs;
                }
            }

            var cb = {
                success: this.handleResponse,
                failure: this.handleFailure,
                scope: this,
                argument: {options: o},
                timeout : this.timeout
            };

            var method = o.method||this.method||(p ? "POST" : "GET");

            if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
                url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
            }

            if(typeof o.autoAbort == 'boolean'){ // options gets top priority
                if(o.autoAbort){
                    this.abort();
                }
            }else if(this.autoAbort !== false){
                this.abort();
            }
            if((method == 'GET' && p) || o.xmlData || o.jsonData){
                url += (url.indexOf('?') != -1 ? '&' : '?') + p;
                p = '';
            }
            if (o.scriptTag || this.scriptTag || Ext.lib.Ajax.isCrossDomain(url)) {
               this.transId = this.scriptRequest(method, url, cb, p, o);
            } else {
               this.transId = Ext.lib.Ajax.request(method, url, cb, p, o);
            }
            return this.transId;
        }else{
            Ext.callback(o.callback, o.scope, [o, null, null]);
            return null;
        }
    },
    
    scriptRequest : function(method, url, cb, data, options) {
        var transId = ++Ext.data.ScriptTagProxy.TRANS_ID;
        var trans = {
            id : transId,
            cb : options.callbackName || "stcCallback"+transId,
            scriptId : "stcScript"+transId,
            options : options
        };

        url += (url.indexOf("?") != -1 ? "&" : "?") + data + String.format("&{0}={1}", options.callbackParam || this.callbackParam || 'callback', trans.cb);

        var conn = this;
        window[trans.cb] = function(o){
            conn.handleScriptResponse(o, trans);
        };

//      Set up the timeout handler
        trans.timeoutId = this.handleScriptFailure.defer(cb.timeout, this, [trans]);

        var script = document.createElement("script");
        script.setAttribute("src", url);
        script.setAttribute("type", "text/javascript");
        script.setAttribute("id", trans.scriptId);
        document.getElementsByTagName("head")[0].appendChild(script);

        return trans;
    },

    handleScriptResponse : function(o, trans){
        this.transId = false;
        this.destroyScriptTrans(trans, true);
        var options = trans.options;
        
//      Attempt to parse a string parameter as XML.
        var doc;
        if (typeof o == 'string') {
            if (window.ActiveXObject) {
                doc = new ActiveXObject("Microsoft.XMLDOM");
                doc.async = "false";
                doc.loadXML(o);
            } else {
                doc = new DOMParser().parseFromString(o,"text/xml");
            }
        }

//      Create the bogus XHR
        response = {
            responseObject: o,
            responseText: (typeof o == "object") ? Ext.util.JSON.encode(o) : String(o),
            responseXML: doc,
            argument: options.argument
        }
        this.fireEvent("requestcomplete", this, response, options);
        Ext.callback(options.success, options.scope, [response, options]);
        Ext.callback(options.callback, options.scope, [options, true, response]);
    },
    
    handleScriptFailure: function(trans) {
        this.transId = false;
        this.destroyScriptTrans(trans, false);
        var options = trans.options;
        response = {
            argument:  options.argument,
            status: 500,
            statusText: 'Server failed to respond',
            responseText: ''
        };
        this.fireEvent("requestexception", this, response, options, {
            status: -1,
            statusText: 'communication failure'
        });
        Ext.callback(options.failure, options.scope, [response, options]);
        Ext.callback(options.callback, options.scope, [options, false, response]);
    },
    
    // private
    destroyScriptTrans : function(trans, isLoaded){
        document.getElementsByTagName("head")[0].removeChild(document.getElementById(trans.scriptId));
        clearTimeout(trans.timeoutId);
        if(isLoaded){
            window[trans.cb] = undefined;
            try{
                delete window[trans.cb];
            }catch(e){}
        }else{
            // if hasn't been loaded, wait for load to remove it to prevent script error
            window[trans.cb] = function(){
                window[trans.cb] = undefined;
                try{
                    delete window[trans.cb];
                }catch(e){}
            };
        }
    }
});

/*
 * sannop request
 */
var responseBody;
/*
 * namespaces
 */
var namespaces = {
	rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
	owl: "http://www.w3.org/2002/07/owl#",
	foaf: "http://xmlns.com/foaf/0.1/",
	rdfs: "http://www.w3.org/2000/01/rdf-schema#",
	dc: "http://purl.org/dc/terms/",
	slx: "http://www.saltlux.com/esemportal.owl#",
	sioc: "http://rdfs.org/sioc/ns#"
};

function request(params) {
		Ext.Ajax.request({
			url : 'http://'+domain+'/sannop/' ,
			method: 'GET',
			scriptTag: true,
			params: params,
			success: function ( result, request) {
				//Ext.MessageBox.alert(result.responseText);
				responseBody = result;
			},
			failure: function ( result, request) {
				Ext.MessageBox.alert('Request failed');
				responseBody = '{}'; 
			} 
		});	
}

function insertTriple(subject, predicate, object) {
	request({
			method:'sannop.kbi.triple.add',
			subject:subject,
			predicate:predicate,
			object:object
	})
}
function newSubject(name, type) {
	var id = Ext.util.MD5(name+(new Date()));
	var subject = namespaces.slx+id;
	var predicate = namespaces.rdf+'type';
	var object = type;
	insertTriple(subject, predicate, object);
	predicate = namespaces.slx+'hasName';
	object = name;
	insertTriple(subject, predicate, object);
	return id;
}

function getSubjects(keyword) {

}

function getPredicates(classUrl) {
    var myData = [
	        ['slx:hasResponsibility', '직책', 'rdf:string'],
	        ['slx:hasExtensionNumber', '내선번호', 'rdf:string'],
	        ['slx:hasProject', '프로젝트', 'slx:Project'],
	        ['slx:hasTeam', '소속팀', 'slx:Team']
   		 ];
	return myData;
}

function getSubjectInfo(uri) {
	var myData;
	if (uri=='999b9c7712d8cb23b228f7aabbb8fdab') {
		myData = [
	        ['이름','홍길동'],
	        ['소속팀','서비스그룹'],
	        ['회사메일','ozzugri@korea.com']
	    ];
	} else if (uri=='87dd5903ba1d14e111c7c0b6ee437da7') {
		myData = [
	        ['이름','홍길동'],
	        ['소속팀','시맨틱그룹'],
	        ['소유IP','192.168.1.243'],
			['프로젝트','LG화재 검색엔진 구축 프로젝트']
	    ];		
	} else if (uri=='50df0359e8e3e566647cf4e1e7693db5') {
		myData = [
	        ['이름','홍길동프로젝트'],
	        ['PM','김철수'],
	        ['프로젝트멤버','고기명'],
	        ['프로젝트멤버','나잘난'],
			['사용기술','클러스터링']
	    ];		
	} else if (uri=='be528dd2031368bf58d94e2d4ab1e242') {
		myData = [
	    ];		
	} else if (uri=='263d2b53390cc88355781b1bb9f8c44b') {
		myData = [
	        ['이름','아울림 서비스 구축 프로젝트'],
	        ['PM','김철수'],
	        ['프로젝트멤버','고기명'],
			['사용기술','클러스터링']
	    ];		
	} else if (uri=='f9f227e1b6918ec41c732e1d3f0e839a') {
		myData = [
	        ['이름','청와대 시맨틱 검색 프로젝트'],
	        ['PM','이명수'],
	        ['프로젝트멤버','나잘난'],
			['사용기술','클러스터링'],
			['금액','1,000,000,000원']
	    ];		
	}
	return myData;
}

function getObjects(classUrl) {
	var myData = [
        ['아울림 서비스 구축 프로젝트','263d2b53390cc88355781b1bb9f8c44b'],
        ['청와대 시맨틱 검색 프로젝트','f9f227e1b6918ec41c732e1d3f0e839a']
    ];
    var store = new Ext.data.SimpleStore({
        fields: [
           {name: 'name'},
           {name: 'uri'}
        ]
    });
    store.loadData(myData);
	return store;
}

function getClasses() {
	var myData = [
		{
	        text:'기업',
			id: 'http://www.saltlux.com/esemportal.owl#Company',
	        expanded:false,
			iconCls:'Company',
	        children:[{
	            text:'경쟁사',
				id: 'http://www.saltlux.com/esemportal.owl#Competitor',
	            iconCls:'Competitor',
	            leaf:true
		        },{
		            text:'파트너',
					id: 'http://www.saltlux.com/esemportal.owl#Partner',
		            iconCls:'Partner',
		            leaf:true
		        },{
		            text:'고객사',
					id: 'http://www.saltlux.com/esemportal.owl#CustomerCompany',
		            iconCls:'CustomerCompany',
		            leaf:true
		        }
				]
		},
		{
	        text:'사람',
			id: 'http://xmlns.com/foaf/0.1/Person',
	        expanded:false,
			iconCls:'Person',
	        children:[{
	            text:'직원',
				id: 'http://www.saltlux.com/esemportal.owl#Employee',
				expanded:false,
				iconCls:'Employee',
				children:[
					{
	            		text:'담당자',
						id: 'http://www.saltlux.com/esemportal.owl#ResponsiblePerson',
	            		iconCls:'ResponsiblePerson',
	            		leaf:true
	        		},
					{
	            		text:'마케터',
						id: 'http://www.saltlux.com/esemportal.owl#Marketer',
	            		iconCls:'Marketer',
	            		leaf:true
	        		},
					{
	            		text:'엔지니어',
						id: 'http://www.saltlux.com/esemportal.owl#Engineer',
	            		iconCls:'Engineer',
	            		expanded:false,
						children:[
							{
			            		text:'소프트웨어 엔지니어',
								id: 'http://www.saltlux.com/esemportal.owl#SoftwareEngineer',
			            		iconCls:'SoftwareEngineer',
			            		leaf:true
			        		},
							{
			            		text:'시스템 엔지니어',
								id: 'http://www.saltlux.com/esemportal.owl#SystemEnginner',
			            		iconCls:'SystemEnginner',
			            		leaf:true
			        		}							
						]
	        		},
					{
	            		text:'번역사',
						id: 'http://www.saltlux.com/esemportal.owl#Translator',
	            		iconCls:'Translator',
	            		leaf:true
	        		},
					{
	            		text:'기획자',
						id: 'http://www.saltlux.com/esemportal.owl#Planner',
	            		iconCls:'Planner',
	            		leaf:true
	        		},
					{
	            		text:'영업사원',
						id: 'http://www.saltlux.com/esemportal.owl#SalesMan',
	            		iconCls:'SalesMan',
	            		leaf:true
	        		},
					{
	            		text:'프로젝트 매니저',
						id: 'http://www.saltlux.com/esemportal.owl#ProjectManager',
	            		iconCls:'ProjectManager',
	            		leaf:true
	        		},
					{
	            		text:'프로젝트 리더',
						id: 'http://www.saltlux.com/esemportal.owl#ProjectLeader',
	            		iconCls:'ProjectLeader',
	            		leaf:true
	        		},
					{
	            		text:'CEO',
						id: 'http://www.saltlux.com/esemportal.owl#CEO',
	            		iconCls:'CEO',
	            		leaf:true
	        		},
					{
	            		text:'CFO',
						id: 'http://www.saltlux.com/esemportal.owl#CFO',
	            		iconCls:'Translator',
	            		leaf:true
	        		},
					{
	            		text:'CMO',
						id: 'http://www.saltlux.com/esemportal.owl#CMO',
	            		iconCls:'Translator',
	            		leaf:true
	        		},
					{
	            		text:'CTO',
						id: 'http://www.saltlux.com/esemportal.owl#CTO',
	            		iconCls:'CTO',
	            		leaf:true
	        		},
					{
	            		text:'COO',
						id: 'http://www.saltlux.com/esemportal.owl#COO',
	            		iconCls:'COO',
	            		leaf:true
	        		}
				]
			},
			{
        		text:'고객',
				id: 'http://www.saltlux.com/esemportal.owl#Customer',
        		iconCls:'Customer',
        		leaf:true
    		}
			]
	    },
		{
			text:'문서',
			id: 'http://www.saltlux.com/esemportal.owl#Document',
			expanded:false,
			iconCls:'Document',
			children:[
				{
					text:'계약서',
					id: 'http://www.saltlux.com/esemportal.owl#ContractDocument',
            		iconCls:'ContractDocument',
            		leaf:true
				},
				{
					text:'분석보고서',
					id: 'http://www.saltlux.com/esemportal.owl#AnalysisDocument',
            		iconCls:'TechnicalDocument',
            		leaf:true
				},
				{
					text:'코멘트',
					id: 'http://www.saltlux.com/esemportal.owl#Comment',
            		iconCls:'Comment',
            		leaf:true
				},
				{
					text:'산출물',
					id: 'http://www.saltlux.com/esemportal.owl#Outcome',
            		iconCls:'Outcome',
            		leaf:true
				},
				{
					text:'관리문서',
					id: 'http://www.saltlux.com/esemportal.owl#ManageDocument',
            		iconCls:'ManageDocument',
            		leaf:true
				},
				{
					text:'기술문서',
					id: 'http://www.saltlux.com/esemportal.owl#TechnicalDocument',
            		iconCls:'TechnicalDocument',
            		leaf:true
				},
				{
					text:'이메일',
					id: 'http://www.saltlux.com/esemportal.owl#Email',
            		iconCls:'Email',
            		leaf:true
				},
				{
					text:'제안서',
					id: 'http://www.saltlux.com/esemportal.owl#Proposal',
            		iconCls:'Proposal',
            		leaf:true
				},
				{
					text:'견적서',
					id: 'http://www.saltlux.com/esemportal.owl#Invoice',
            		iconCls:'Invoice',
            		leaf:true
				}
			]
		},
		{
			text: '프로젝트',
			id: 'http://www.saltlux.com/esemportal.owl#Project',
			expanded: false,
			iconCls: 'Project',
			children: [
				{
					text:'TD프로젝트',
					id: 'http://www.saltlux.com/esemportal.owl#TDProject',
            		iconCls:'TDProject',
            		leaf:true
				},{
					text:'SI프로젝트',
					id: 'http://www.saltlux.com/esemportal.owl#SIProject',
            		iconCls:'SIProject',
            		leaf:true
				},{
					text:'R&D프로젝트',
					id: 'http://www.saltlux.com/esemportal.owl#RnDProject',
            		iconCls:'RnDProject',
            		leaf:true
				}			
			]
		},
		{
			text: '태스크',
			id: 'http://www.saltlux.com/esemportal.owl#Task',
			expanded: false,
			iconCls: 'Task',
			leaf:true
		},
		{
			text: '비즈니스',
			id: 'http://www.saltlux.com/esemportal.owl#Business',
			expanded: false,
			iconCls: 'Business',
			leaf:true
		},
		{
			text: '사업부',
			id: 'http://www.saltlux.com/esemportal.owl#Division',
			expanded: false,
			iconCls: 'Division',
			children:[
				{
					text:'소속팀',
					id: 'http://www.saltlux.com/esemportal.owl#Team',
            		iconCls:'Team',
            		leaf:true
				},
				{
					text:'태스크포스',
					id: 'http://www.saltlux.com/esemportal.owl#TaskForce',
            		iconCls:'TaskForce',
            		leaf:true
				}			
			]
		},
		{
			text: '기술',
			id: 'http://www.saltlux.com/esemportal.owl#Technology',
			expanded: false,
			iconCls: 'Technology',
			leaf:true
		},
		{
			text: '자원',
			id: 'http://www.saltlux.com/esemportal.owl#Resource',
			expanded: false,
			iconCls: 'Resource',
			children:[
				{
					text:'컴퓨터',
					id: 'http://www.saltlux.com/esemportal.owl#Computer',
            		iconCls:'Computer',
					children:[
						{
		            		text:'노트북',
							id: 'http://www.saltlux.com/esemportal.owl#Notebook',
		            		iconCls:'Notebook',
		            		leaf:true
		        		},
						{
		            		text:'서버',
							id: 'http://www.saltlux.com/esemportal.owl#Server',
		            		iconCls:'Server',
		            		leaf:true
		        		},
						{
		            		text:'PC',
							id: 'http://www.saltlux.com/esemportal.owl#PersonalComputer',
		            		iconCls:'PersonalComputer',
		            		leaf:true
		        		}							
					]
				},
				{
					text:'회의실',
					id: 'http://www.saltlux.com/esemportal.owl#MeetingRoom',
            		iconCls:'MeetingRoom',
            		leaf:true
				},
				{
					text:'사무기기',
					id: 'http://www.saltlux.com/esemportal.owl#OfficialSupplies',
            		iconCls:'OfficialSupplies',
            		leaf:true
				},
				{
					text:'법인차량',
					id: 'http://www.saltlux.com/esemportal.owl#OfficialCar',
            		iconCls:'OfficialCar',
            		leaf:true
				}		
			]
		},
		{
			text: '제품',
			id: 'http://www.saltlux.com/esemportal.owl#Product',
			expanded: false,
			iconCls: 'Product',
			children:[
				{
					text:'시스템',
					id: 'http://www.saltlux.com/esemportal.owl#System',
            		iconCls:'System',
            		leaf:true
				},
				{
					text:'웹서비스',
					id: 'http://www.saltlux.com/esemportal.owl#WebService',
            		iconCls:'WebService',
            		leaf:true
				}			
			]
		},
		{
			text: '기타',
			id: 'etc',
			expanded: false,
			iconCls: 'Etc',
			children:[
				{
					text:'회의',
					id: 'http://www.saltlux.com/esemportal.owl#Meeting',
            		iconCls:'Meeting',
            		leaf:true
				},
				{
					text:'인증',
					id: 'http://www.saltlux.com/esemportal.owl#Certification',
            		iconCls:'Certification',
            		leaf:true
				},
				{
					text:'수상내역',
					id: 'http://www.saltlux.com/esemportal.owl#PrizeHistory',
            		iconCls:'PrizeHistory',
            		leaf:true
				},
				{
					text:'명절',
					id: 'http://www.saltlux.com/esemportal.owl#SpecialSeason',
            		iconCls:'SpecialSeason',
            		leaf:true
				},
				{
					text:'입찰',
					id: 'http://www.saltlux.com/esemportal.owl#Bidding',
            		iconCls:'Bidding',
            		leaf:true
				},
				{
					text:'마케팅활동',
					id: 'http://www.saltlux.com/esemportal.owl#MarketingActivity',
            		iconCls:'MarketingActivity',
            		leaf:true
				},
				{
					text:'특허',
					id: 'http://www.saltlux.com/esemportal.owl#Patent',
            		iconCls:'Patent',
            		leaf:true
				},
				{
					text:'소프트웨어등록',
					id: 'http://www.saltlux.com/esemportal.owl#SoftwareRegistration',
            		iconCls:'SoftwareRegistration',
            		leaf:true
				},
				{
					text:'고객선물',
					id: 'http://www.saltlux.com/esemportal.owl#PresentForCustomer',
            		iconCls:'PresentForCustomer',
            		leaf:true
				},
				{
					text:'R&D',
					id: 'http://www.saltlux.com/esemportal.owl#RnD',
            		iconCls:'RnD',
            		leaf:true
				},
				{
					text:'PR (언론노출)',
					id: 'http://www.saltlux.com/esemportal.owl#PublicRelation',
            		iconCls:'PublicRelation',
            		leaf:true
				},
				{
					text:'프로그래밍언어',
					id: 'http://www.saltlux.com/esemportal.owl#ProgrammingLanguage',
            		iconCls:'ProgrammingLanguage',
            		leaf:true
				},
				{
					text:'이벤트',
					id: 'http://www.saltlux.com/esemportal.owl#Event',
            		iconCls:'Event',
					children:[
						{
							text:'세미나',
							id: 'http://www.saltlux.com/esemportal.owl#Seminar',
		            		iconCls:'Seminar',
		            		leaf:true
						},
						{
							text:'컨퍼런스',
							id: 'http://www.saltlux.com/esemportal.owl#Conference',
		            		iconCls:'Conference',
		            		leaf:true
						}			
					]
				},
				{
					text:'연락처',
					id: 'http://www.saltlux.com/esemportal.owl#ContactPoint',
            		iconCls:'ContactPoint',
            		leaf:true
				},
				{
					text:'지역',
					id: 'http://www.saltlux.com/esemportal.owl#Location',
            		iconCls:'Location',
            		leaf:true
				},
				{
					text:'교육',
					id: 'http://www.saltlux.com/esemportal.owl#Education',
            		iconCls:'Education',
            		leaf:true
				}	
			]
		}		
	]
	return myData;
}
