/*
$Date: 2017-10-23 11:38:38 +0300 (Pr, 23 Spl 2017) $ 
$Rev: 17854 $ 
$HeadURL: https://svn.eypsise/channels/LiveBranch/Unet3UusKujundus/un3webipank/resp/js/usearch.js $ 
$Author: rain $
*/


// create local scope with an anonymous function
usearch = {
    
    sesskey : "",
    un3act : "",
    lang : "",
    
    makeSearchURL: function () {
        
        var argbeg;
        var argend;
        //var url=window.location.protocol+"//"+window.location.host+window.location.pathname+"?";
		var url=UserSetupArray[8]+"?";
        var argument = "";
    
        for (var i=0;i<arguments.length;i++) {
            
            argument = arguments[i].toString();
            argbeg = argument.substr(0,argument.indexOf("="));
            argend = argument.substr(argument.indexOf("=")+1);
            url += encodeURIComponent(argbeg) + "=" + encodeURIComponent(argend) + "&";
                        
        }
        
        url+="lang="+this.lang+"&rId="+(new Date()).getTime();
        if (this.un3act>"")
            url+="&act="+this.un3act;
        url+="&sesskey="+this.sesskey;
        return url;
    },
    

    xmlhttp: null,
    
    doAjaxRequest: function (url) {
		url=url.substr(0,url.lastIndexOf('=')+1); //hack, et j22ksid käima nii getSuggestion kui Otsing ise
		
		if (global_ajaxeventrunning) { //kui on teisi hetkel k2imasolevaid ajaxp2ringuid, siis tehakse antud p2ring hiljem - ainult yks ajax p2ring paralleelselt (sessiooni aegumisel v2lja lendamise v2listamine ajax p2ringu puhul)
	        global_ajaxstack.push([this.doAjaxRequest,this,[url]]);
	        return;
	    }

		url+=this.sesskey; //hack, et j22ksid käima nii getSuggestion kui Otsing ises
		
		$.ajax({
			url: url,
			cache: false,
			success: function(html) {
				
                try{
                    if (html.substr(html.length-1)=='$'&&html.indexOf('id="loginpage"')===-1) {
                        var sesskeystart = html.lastIndexOf('$',html.length-2),
                            newsesskey = html.substring(sesskeystart+1,html.length-1),
                            html=html.substring(0,sesskeystart),
                            links=$('a[href*="sesskey="]'),
                            href,
                            link,
                            i = links.length,
                            oldsesskey=document.forms.sessionData.sesskey.value;
                        while(i) {
                            i--;
                            link=$(links[i]);
                            href=link.attr('href').replace(oldsesskey,newsesskey);
                            link.attr('href',href);
                        }
                        $('input[value="'+oldsesskey+'"]').val(newsesskey);
                        //usearch.initParams();
                        usearch.sesskey=newsesskey;
                        //updateSesskeyInVariables(window,oldsesskey,newsesskey);
                        $('#searchid001').setOptions({'url':usearch.makeSearchURL("sact=getsuggestion")});
                    }
                    
                    if (html.indexOf("id=\"timeout_page\"")>=0) {
                        var element = $('#timeout_page');
                        if (element.length===0) {
                            $("#messages").append(html);
                            tb_show("", "#TB_inline?height=400&width=600&inlineId=timeout_page&modal=true", null);
                        }
                    } else if (html.indexOf("id=\"loginpage\"")>=0) {
                        $("html").html(html);
                    } else {
                       answer=JSON.parse(html);   
                       
                       if (answer) {
                    
                            if (answer.length>0) {
                                usearch.handleAjaxAnswer(answer);
                            }
                            
                        }
                        else {
                            alert("The 'answer' does not exist or is not an array of objects!");
                        }
                       
                    }
                    
                }
                catch(e){
                    alert("Error: " + e); //usearch.xmlhttp.responseText
                }

                delete answer;
				
				
			}
		});
        
    },
    
	
    doSearch: function() {  
        var inpval=document.getElementById("searchid001").value;
        if(!inpval||inpval=="")return false;
        
        this.doAjaxRequest(this.makeSearchURL("sact=searchreq", "keyword=" + inpval, "mmtype=EMK"));

        return false;
        
    },
     
	
    handleAjaxAnswer: function(answer) {
    
        if (typeof(answer) == "object") {
        
            var destination;
            var html;
        
            for (var i = 0; i < answer.length; i++) {
            
                switch (answer[i].type) {
                    case "searchReq": //USERSEARCH
                        destination = document.getElementById(answer[i].destination);
                        destination.innerHTML = "";
                        usearch.searchReq(answer[i].data, destination, answer[i].keyword, answer[i].paymgrouptext, answer[i].howmanytext1, answer[i].howmanytext2, answer[i].header, answer[i].rightcolhtml);
                        break;
                    case "getSymbErr":
                        document.getElementById("headermain").innerHTML = answer[i].header;
                        document.getElementById("mainwincell").innerHTML = '<div class="block01 block01-expandable block01-expandable-open clear"><div class="block01-a clear"><div class="block01-b clear mt5"><div class="block01-c clear"><div class="block01-d clear"><div class="w100p"><ul class="messages clear"><li class="negative"><p>'+answer[i].errmessage+'</p></li></ul></div></div></div></div></div></div>';
                        break;
                        
                }
                
            }
            
        }
    
    },
        
    searchReq: function (data,destination,keyword,paymgrouptext,howmanytext1,howmanytext2,header,rightcolhtml) {
        
        var url;

        var temp;
        var temp2;
        var temp3;
        
        $('.tabs01').remove();
        
        document.getElementById("headermain").innerHTML = header;

        var main = document.createElement("div");
        main.id = "searchmainid";
        main.className = "clear";
        destination.appendChild(main);

        if (rightcolhtml!="") {
            temp2 = document.createElement("div");
            temp2.className = "col col01";
            main.appendChild(temp2);
    
            temp = document.createElement("div");
            temp.className = "block01 block01-expandable block01-expandable-open clear";
            temp2.appendChild(temp);
        } else {
            temp = document.createElement("div");
            temp.className = "block01 block01-expandable block01-expandable-open clear";
            main.appendChild(temp);
        }

        temp2 = document.createElement("div");
        temp2.className = "block01-a clear";
        temp.appendChild(temp2);
        temp = document.createElement("div");
        temp.className = "block01-b clear mt5";
        temp2.appendChild(temp);
        temp2 = document.createElement("div");
        temp2.className = "block01-c clear";
        temp.appendChild(temp2);
        temp = document.createElement("div");
        temp.className = "block01-d clear";
        temp2.appendChild(temp);

        var searchplace = document.createElement("div");
        searchplace.className = "w100p";
        temp.appendChild(searchplace);


        
        var howmanyplace = document.createElement("ul");
        howmanyplace.className = "messages clear";
        searchplace.appendChild(howmanyplace);
        var howmanyplace1 = document.createElement("li");
        howmanyplace.appendChild(howmanyplace1);
        var howmanyplace2 = document.createElement("p");
        howmanyplace1.appendChild(howmanyplace2);
        


        for (var i=0;i<data.search.length;i++) {

            if (document.getElementById(data.search[i].group+"_id")==null) {
                temp = document.createElement("h2");
                temp.innerHTML = data.search[i].group;
                searchplace.appendChild(temp);

                temp = document.createElement("div");
                temp.className = "searchresults01";
                searchplace.appendChild(temp);

                temp2 = document.createElement("ul");
                temp2.className = "a clear";
                temp2.id = data.search[i].group+"_id";
                temp.appendChild(temp2);

                temp = document.createElement("div");
                temp.className = "separator01";
                searchplace.appendChild(temp);

                temp2 = document.createElement("hr");
                temp.appendChild(temp2);

            }

            if (data.search[i].link.indexOf("?")===0) {
                 url=UserSetupArray[8]+data.search[i].link+"&sesskey="+this.sesskey+"&lang ="+this.lang;
            } else {
                url=data.search[i].link;
            }

            temp = document.createElement("li");
            temp.className = "item";
            document.getElementById(data.search[i].group+"_id").appendChild(temp);
            
            temp2 = document.createElement("div");
            temp2.className = "txt";
            temp.appendChild(temp2);

            temp = document.createElement("h3");
            temp2.appendChild(temp);

            temp3 = document.createElement("a");
            temp3.href = url;
            temp3.innerHTML = data.search[i].description;
            temp.appendChild(temp3);

            temp = document.createElement("p");
            temp.innerHTML = data.search[i].explanation;

            temp2.appendChild(temp);


        }

        var count = 0;
        
            keyword = keyword.toUpperCase();

        for (var i = 0; i < data.paym.items.length; i++) {
            if (data.paym.items[i].crname.toUpperCase().indexOf(keyword)>=0||
                data.paym.items[i].craaa.toUpperCase().indexOf(keyword)>=0||
                data.paym.items[i].desc.toUpperCase().indexOf(keyword)>=0||
                data.paym.items[i].refnr.toUpperCase().indexOf(keyword)>=0) {


                if (document.getElementById("paym_id")==null) {

                    temp = document.createElement("h2");
                    temp.innerHTML = paymgrouptext;
                    searchplace.appendChild(temp);
    
                    temp = document.createElement("div");
                    temp.className = "searchresults01";
                    searchplace.appendChild(temp);
    
                    temp2 = document.createElement("ul");
                    temp2.className = "a clear";
                    temp2.id = "paym_id";
                    temp.appendChild(temp2);
    
                    temp = document.createElement("div");
                    temp.className = "separator01";
                    searchplace.appendChild(temp);
    
                    temp2 = document.createElement("hr");
                    temp.appendChild(temp2);

                }
                if (data.appname&&data.appname==="IFIRMA")
				    url=UserSetupArray[8] + "?act=SMARTPAYM&mmacc=MMBREQ&mmnr=" + data.paym.items[i].mmnr + "&reqnr=" + data.paym.items[i].mmnr + "&sesskey=" + this.sesskey + "&lang=" + this.lang;
				else
                    url=UserSetupArray[8] + "?act=SMARTPAYM&mmacc=" + data.paym.items[i].dbaaa + "&mmnr=" + data.paym.items[i].mmnr + "&sesskey=" + this.sesskey + "&lang=" + this.lang;

        
                temp = document.createElement("li");
                temp.className = "item";
                document.getElementById("paym_id").appendChild(temp);
    
                temp2 = document.createElement("div");
                temp2.className = "txt";
                temp.appendChild(temp2);
    
                temp = document.createElement("h3");
                temp2.appendChild(temp);
    
                temp3 = document.createElement("a");
                temp3.href = url;
                temp3.innerHTML = data.paym.items[i].label;
                temp.appendChild(temp3);
    
                temp = document.createElement("p");
                temp.innerHTML = data.paym.items[i].desc;
    
                temp2.appendChild(temp);

                count++;

            }
        }

    

        howmanyplace2.innerHTML = howmanytext1+" "+(data.search.length+count)+" "+howmanytext2 + " \"" + keyword.replace(/</g,"&lt;") + "\"";
    
        /*TIPPIDE OSA*/

        if (rightcolhtml!="") {
            temp = document.createElement("div");
            temp.className = "col col02";
            temp.innerHTML = rightcolhtml;
            main.appendChild(temp);
        }
    
        if (data.search.length+count===1) {
            window.location=url;
        }

        initsieeri("#searchmainid");
        
    },
    
    initParams: function() {
        this.un3act="USEARCH";
        var inpflds=document.getElementsByTagName("INPUT");
        for (i=0;i<inpflds.length;i++){
            if(inpflds[i].name=="sesskey"&&inpflds[i].value!="")
                this.sesskey=inpflds[i].value;
            if(inpflds[i].name=="unetlanguage"&&inpflds[i].value!="")
                this.lang=inpflds[i].value;
        }
        window["ajaxcallback_TIME_USEARCH"] = usearch.handleAjaxAnswer;
        return false;
    }
    
};

$(document).ready(function(){
	usearch.initParams();
	$('#searchid001').autocomplete({
	    source: usearch.makeSearchURL("sact=getsuggestion","mmtype=EMK"),
	    //source: "data/search01.php",
	    minLength: 3,
	    position: { offset: "0 3" },
	    select: function (event, ui) {
	        //console.log( ui.item ? "Selected: " + ui.item.value + " aka " + ui.item.id : "Nothing selected, input was " + this.value );
	    	usearch.doSearch();
	    },
	    close: function () {
	        if (getMedia() === 'narrow') {
			$(this).autocomplete('option', 'appendTo', '#menu01');
		  } else {
			$(this).autocomplete('option', 'appendTo', '');
		  } 
	    },
	    open: function () {
	        if (getMedia() === 'narrow') {
			$(this).autocomplete('option', 'appendTo', '#menu01');
		  } else {
			$(this).autocomplete('option', 'appendTo', '');
		  } 
	    }
	});
        $('#searchid001').on('keypress',function(e) {
           if (e.which === 13) {
                usearch.doSearch();
           }
        });
});
