/********************************************************************************
 *
 * yometa main javascript file
 *
 */
var isdebug = false;
var scrollOverTID =null;

function Desktop(search_str) {
    this.init();

    this.cfg = {
        hasSizeBtn: false,
        hasRefreshBtn: false,
        hasSettingsBtn: false,
        hasDrag: false,
        isOpenHidden: false,
        isSystem: true,
        module: "Desktop",
        isWindow: false
    }

    this.widget = null;


//    this.busy = [];
    // precal coordinates
    this.precalc = [ [], [], [], [], [],[], []];
    this.image_width = 497;
    this.image_height = 495;
    this.circle_radius = 164;
    this.minicircle_radius = 33;
    // zone radius where pins never been
    this.death_zone = 10;

    // pin width and height + some values
    this.pinWidth = 14;
    this.pinHeight = 14;
    this.searchTimeoutValue = 20000;
    this.scrollOverTimeout = 500;
    this.pageScrollStep = 10;
    this.topmost_cl_number = 4;
    this.searchTimeoutId = -1;
    this.busyCoords = [];
    this.squaresNum = 8;

    this.firstSearchStr = search_str;


  /*  this.isBusy = function(coord) {
        // check if coord in busy array

        for (var i =0; i< this.busy.length; i++) {
            if (this.busy[i].x == coord.x &&
                    this.busy[i].y == coord.y) {

                return 1;
            }
        }
        return 0;
    }*/



    this.clearPrecalc = function() {
        this.busyCoords = [];
        for(var i=0; i<this.precalc.length; i++) {
            for(var j=0; j<this.precalc[i].length; j++) {
                this.precalc[i][j].b = 0;
            }
        }
    }


    this.loadSettings = function() {
        //this.showLayer();
        request.send({ 'get_settings': '1'}, this);
    }

    this.handleResize = function() {

        if (this.layerShowed == 1) {
            var rect = system.getWindowRect();
            system.setElementRect(this.elements["cover_layer"], rect);

        }
        //this.doPrecalculations;
    }

    this.doPrecalculations = function() {
        // step in pixels
        var stepx = this.pinWidth;
        var stepy = this.pinHeight;
        var death_zone = this.death_zone;



        var google_rad;
        var yahoo_rad;
        var msn_rad;

        with (Math) {
            for (var y =0;y<this.image_width;y+=stepy) {
                for (var x =0;x<this.image_width;x+=stepx) {

                    var idx = -1;
                    var google_rad = sqrt(pow(y-this.coords[0].y,2)+pow(x-this.coords[0].x,2));
                    var yahoo_rad = sqrt(pow(y-this.coords[1].y,2)+pow(x-this.coords[1].x,2));
                    var msn_rad = sqrt(pow(y-this.coords[2].y,2)+pow(x-this.coords[2].x,2));

                    if ( google_rad <= this.circle_radius
                        &&
                        yahoo_rad > this.circle_radius+death_zone
                        &&
                        msn_rad > this.circle_radius+death_zone) {
                            // google
                            idx =0;

                    }
                    else
                    if (google_rad > this.circle_radius+death_zone
                        &&
                        yahoo_rad <= this.circle_radius
                        &&
                        msn_rad > this.circle_radius+death_zone) {
                        // yahoo
                        idx =4;

                    }
                    else
                    if (google_rad > this.circle_radius+death_zone
                            &&
                            yahoo_rad > this.circle_radius+death_zone
                            &&
                            msn_rad <= this.circle_radius) {
                            // msn
                            idx =6;

                    }
                    else
                    if (google_rad <= this.circle_radius
                        &&
                        yahoo_rad <= this.circle_radius
                        &&
                        msn_rad > this.circle_radius+death_zone) {
                        // google && msn
                        idx =1;

                    }
                    else
                    if (google_rad > this.circle_radius+death_zone
                        &&
                        yahoo_rad <= this.circle_radius
                        &&
                        msn_rad <= this.circle_radius) {

                        // yahoo && msn
                        idx =5;

                    }
                    else
                    if (google_rad <= this.circle_radius
                        &&
                        yahoo_rad > this.circle_radius+death_zone
                        &&
                        msn_rad <= this.circle_radius) {
                            idx =3;

                    }
                    else
                    if (google_rad <= this.circle_radius
                        &&
                        yahoo_rad <= this.circle_radius
                        &&
                        msn_rad <= this.circle_radius) {
                            idx =2;
                    }

                    if (idx>-1) {
                        this.precalc[idx][this.precalc[idx].length] = {c: {x:x, y:y}, b: 0, "idx": idx};
                    }
                }

            }


        }

    }

    this.findBestCoords = function(ses, jj, adv) {

        var idx = -1;

        if (ses.google == '1' && ses.yahoo == null && ses.msn == null) {
            idx=0;
        }
        else
        if (ses.google == null && ses.yahoo == '1' && ses.msn == null) {
            idx=4;
        }
        else
        if (ses.google == null && ses.yahoo == null && ses.msn == '1') {
            idx=6;

        }
        else
        if (ses.google == '1' && ses.yahoo == '1' && ses.msn == null) {
            idx=1;
        }
        else
        if (ses.google == null && ses.yahoo == '1' && ses.msn == '1') {
            idx=5;
        }
        else
        if (ses.google == '1' && ses.yahoo == null && ses.msn == '1') {
            idx=3;

        }
        else
        if (ses.google == '1' && ses.yahoo == '1' && ses.msn == '1') {
            idx=2;

        }

        var rnd;
        var isbusy = 1;
        var i = 0;



        while (isbusy == 1) {

            i++;
            if (adv == true) {

                rnd = 31;
            }
            else {
                rnd = Math.round(Math.random()*(this.precalc[idx].length-1)) ;
                if (jj< 4) {

                    switch (idx) {

                        case 0:
                            rnd = this.precalc[idx].length - Math.round(Math.random()*10);
                        break;

                        case 1:
                            rnd = Math.round(Math.random()*10)+ 5 ;
                        break;

                        case 2:
                            rnd = Math.round(Math.random()*5)+ 1 ;
                        break;

                        case 3:
                            rnd = Math.round(Math.random()*10)+ 10 ;
                        break;

                        case 4:
                            rnd = Math.round(Math.random()*10)+ 40 ;
                        break;

                        case 5:
                            rnd = Math.round(Math.random()*10)+ 5 ;
                        break;

                        case 6:
                            rnd = Math.round(Math.random()*10)+ 20 ;
                        break;

                    }

                    if (rnd>= this.precalc[idx].length) {
                        rnd = this.precalc[idx].length - 1;

                    }
                    else
                    if (rnd< 0) {
                        rnd = 0;

                    }

                }

            }
            if (isdebug) {
                console.log('query_result: while isbusy', rnd, this.precalc[idx].length);
            }
            if (this.precalc[idx][rnd].b == 0 || i > 40) {

                if (isdebug) {
                    console.log('query_result: while isbusy IF');
                }
                // make coord busy
                this.precalc[idx][rnd].b = 1;
                //this.precalc[idx][rnd].rnd = rnd;
                isbusy = 0;

                this.busyCoords[this.busyCoords.length] = {};
                //this.busyCoords[this.busyCoords.length].c = {x: this.precalc[idx][rnd].c.x
                //    , y: this.precalc[idx][rnd].c.y};
                return this.precalc[idx][rnd];
            }
        }

        // found

        return {c: {x: -1,y: -1}, idx: -1};
    }


    this.miniCirclesClick = function (event) {

        //var x = event.clientX-getLeft(this.elements["mini_circ_img"]);
        //var y = event.clientY-getTop(this.elements["mini_circ_img"]);
        event = fix_event(event);
        var coordX = event.clientX + document.body.scrollLeft;
        var coordY = event.clientY + document.body.scrollTop;

        var x = coordX-getLeft(this.elements["mini_circ_img"]);
        var y = coordY-getTop(this.elements["mini_circ_img"]);


        //alert(coordX+':'+coordY);
        //alert(getLeft(this.elements["mini_circ_img"])+':'+getTop(this.elements["mini_circ_img"]));
        var idx = -1;




        with (Math) {
            var google_rad = sqrt(pow(y-this.minicoords[0].y,2)+pow(x-this.minicoords[0].x,2));
            var yahoo_rad = sqrt(pow(y-this.minicoords[1].y,2)+pow(x-this.minicoords[1].x,2));
            var msn_rad = sqrt(pow(y-this.minicoords[2].y,2)+pow(x-this.minicoords[2].x,2));

            if ( google_rad <= this.minicircle_radius
                &&
                yahoo_rad > this.minicircle_radius
                &&
                msn_rad > this.minicircle_radius) {
                    // google
                    idx =0;

            }
            else
            if (google_rad > this.minicircle_radius
                &&
                yahoo_rad <= this.minicircle_radius
                &&
                msn_rad > this.minicircle_radius) {
                // yahoo
                idx =4;

            }
            else
            if (google_rad > this.minicircle_radius
                    &&
                    yahoo_rad > this.minicircle_radius
                    &&
                    msn_rad <= this.minicircle_radius) {
                    // msn
                    idx =6;

            }
            else
            if (google_rad <= this.minicircle_radius
                &&
                yahoo_rad <= this.minicircle_radius
                &&
                msn_rad > this.minicircle_radius) {
                // google && msn
                idx =1;

            }
            else
            if (google_rad > this.minicircle_radius
                &&
                yahoo_rad <= this.minicircle_radius
                &&
                msn_rad <= this.minicircle_radius) {

                // yahoo && msn
                idx = 5;

            }
            else
            if (google_rad <= this.minicircle_radius
                &&
                yahoo_rad > this.minicircle_radius
                &&
                msn_rad <= this.minicircle_radius) {
                    idx = 3;

            }
            else
            if (google_rad <= this.minicircle_radius
                &&
                yahoo_rad <= this.minicircle_radius
                &&
                msn_rad <= this.minicircle_radius) {
                    idx =2;

            }
        }


        // clear selection
        if (this.lastMinicIdx == idx) {


            this.filterPins(-1);
            this.lastMinicIdx = -2;
            this.elements["mini_circ_img"].src = 'img/mini_circles.gif';
            return 1;
        }


        if (idx>-1) {
            this.filterPins(idx);

            this.lastMinicIdx = idx;
            this.elements["mini_circ_img"].src = 'img/mini_circles_'+idx+'.gif';
            //alert(this.elements["mini_circ_img"].src);
        }
        else {
            this.filterPins(-1);
            this.elements["mini_circ_img"].src = 'img/mini_circles.gif';
        }

    }

    this.filterPins = function(idx){
        if (this.pinsCount>0) {
            this.curFilter = idx;
            for (var i= 0; i<this.pinsCount; i++) {

                var el = this.elements["pin_res_"+i];

                //alert(el);

                    if (idx>-1) {
                        if (el.my_area_idx != idx) {
                            this.busyCoords[i].tt.style.display = 'none';
                            this.hideElement("pin_res_"+i);
                        }
                        else {
                            //this.busyCoords[i].tt.style.display = '';
                            //ttShow(this.busyCoords[i].tt.style.display);
                            this.showElement("pin_res_"+i);
                        }
                    }
                    else {
                        this.showElement("pin_res_"+i);
                    }
            }

        }
    }

    // shows fadin layer and loading image
    this.showLayer = function() {

        var rect = system.getWindowRect();
        system.setElementRect(this.elements["cover_layer"], rect);
        this.showElement("cover_layer");
        system.startFadeIn(this.elements["cover_layer"]);

        this.elements["loading"].style.left = rect.width/2-75+"px";
        this.elements["loading"].style.top = rect.height/2-50-this.elements["loading"].style.height/2+"px";

        this.showElement("loading");
        this.layerShowed = 1;
    }

    this.hideLayer = function() {
        this.hideElement("loading");
        system.startFadeOut(this.elements["cover_layer"]);
        this.layerShowed = 0;
    }

    // search action
    this.checkSearchKeyUp = function(e) {
        var code = e.which ? e.which : e.keyCode;
        if( code == 13) {
            this.scrollSearch(1, true);
            //this.doSearch();
        }

    }

    // search action
    this.doSearch = function(from) {
        var t = this;
        if (from == null) {
            from = 0;
        }

        this.showLayer();
        /*var showLayer = function( ) {


        }

        showLayerId = setTimeout( showLayer, this.showLayerValue);
        */
        window.onresize = this.handleResize;


        // search timeout
        var searchTimeOut = function() {
            t.hideLayer();
            t.showNotifyMessage('Error! Timeout while fetching search results.');
            t.searchTimeoutId = -1;
        }

        request.send({ 'query': this.elements['input_search'].value
                        , 'from' : from
                        , 'step' : this.pageScrollStep
                        , 'mfrom' : this.mfrom}, this);
        this.searchTimeoutId = setTimeout( searchTimeOut, this.searchTimeoutValue);
    }


    // notify message layer
    this.showNotifyMessage = function (msg) {

        var rect = system.getWindowRect();
        var nm = this.elements['notify_message'];

        nm.style.display = 'block';
        nm.style.left = (rect.width-nm.offsetWidth-30)+"px";
        nm.style.top = (rect.height-nm.offsetHeight-20)+"px";
        this.elements['nmmessage'].innerHTML = msg;


    }

    // hide notify message layer
    this.hideNotifyMessage = function () {

        this.elements['notify_message'].style.display = 'none';
    }

    this.coords = [{x: 254, y: 166},
                   {x: 170, y: 331},
                   {x: 335, y: 331}
                    ];
    this.minicoords = [{x: 48, y:33},
                       {x: 33, y:67},
                       {x: 66, y:66}
                        ]

    this.scrollMouseOut = function(idx){
        if(scrollOverTID != null) {
            clearTimeout(scrollOverTID);
            scrollOverTID = null;
        }


        if (idx != this.curSquare) {
            var el = this.elements["square_"+idx];

            el.className = "square";
        }


    }

    this.scrollMouseOver = function(idx){
        // do color yellow box

        if (idx != this.curSquare) {
        //alert('over');
            var el = this.elements["square_"+idx];

            el.className = "square_hover";
        }


        //settimeout
        var th = this;
        var idxthis = idx;
        var f = function () {
            th.scrollDo(idxthis);
            scrollOverTID = null;
        }
        scrollOverTID = setTimeout(f, this.scrollOverTimeout);

    }

    /* scroll */
    this.scrollDo = function(idx) {
        this.elements['square_'+this.curSquare].className = "square";
        this.elements['square_'+idx].className = "square_border";
        this.curSquare = this.elements['square_'+idx].my_nmb;

        this.showCallouts();

    }

    this.searchUp = function(){
         //alert(this.curSquare);
         if (this.elements['input_search'].value == '') {
            this.showNotifyMessage('Search input is empty!');
         }
         else {
             var idx = parseInt(this.curPage)+1;
             //this.elements["scroll_prev"].style.display = 'block';
             this.elements["scroll_prev"].style.visibility = 'visible';
             if (idx<=10) {
                 this.scrollSearch(idx);
             }
         }
    }

    this.searchBottom = function(){
        if (this.elements['input_search'].value == '') {
            this.showNotifyMessage('Search input is empty!');
         }
         else {
             var idx = parseInt(this.curPage)-1;
             if (idx == 1) {
                //this.elements["scroll_prev"].style.display = 'none';
                this.elements["scroll_prev"].style.visibility = 'hidden';

             }
             if (idx>0) {
                 this.scrollSearch(idx);
             }
         }
    }


    this.scrollSearch = function (id, force) {

        if (this.elements['input_search'].value == '') {
            this.showNotifyMessage('Search input is empty!');
        }
        else {
            if (this.curPage != id) {

                this.curPage = id;
                this.doSearch((this.elements['square_'+id].my_nmb-1)*10);
            }
            else
            if (force){
                this.doSearch();
            }
        }

    }

    this.domModel = [
        { tag: "div", cn: "header_box",
          childs: [
            { tag: "div", cn: "header_title"
            , html: "Search results from: <font color=red>Google</font>, <font color=green>Yahoo</font>, <font color=blue>Bing Search</font>"}

          ]
        },

        { tag: "div",  id: "loading", cn: "loading",
            childs: [
                { tag: "img",  src: 'img/circle_animation.gif' }
            ]
        }
        ,

        { tag: "div", cn: "main_box",
          childs: [
            { tag: "div", cn: "main_left"
                , childs: [
                    { tag: "img", cn: "do_center", src: "img/yometa.png" },
                    { tag: "div",  cn: "search_input",
                        childs: [
                            { tag: "input", type: "text", id: "input_search",  events: {onkeyup: "checkSearchKeyUp(event)"} }
                        ]},

                    { tag: "div", cn: "search_btn",
                        childs: [
                            { tag: "input", type: "button", value: " Search ", events: {onclick: "scrollSearch(1,true)"}}
                        ]},
                    { tag: "div", cn: "links",
                        childs: [
                            { tag: "a", cn: "links", href: "void", events: {onclick: "goAboutLink()"}, html: "About yometa"},
                            { tag: "a", cn: "links", style : {marginLeft: "20px"},  href: "void", events: {onclick: "goBlogLink()"}, html: "How To Use"}
                        ]},
                    { tag: "div", cn: "controller",
                        childs: [
                            { tag: "div",  id:"scroller", cn: "scroller",
                                childs: [
                                ]},
                            { tag: "div", cn: "mini_circles", id: "mini_circles",
                                childs: [
                                    { tag: "div", cn:"mini_circles_img",
                                        childs: [
                                        { tag: "img",  id:"mini_circ_img", src: "img/mini_circles.gif", events: {onclick: "miniCirclesClick(event)"} }
                                    ]},

                                    { tag: "div", id:"pages_text",  cn:"pages_text", html: ""}
                                ]
                            }
                        ]}
                ]
            },
            { tag: "div", id: "main_div", cn: "main_right"
                , childs: [

                    { tag: "img", id: "img_circles",  cn: "do_center", src: "img/circles.png" }

                ]
            },
            {tag: "div", id: "main_circles", cn: "main_circles"}
            ,
        {tag: "div", id: "notify_message", cn: "notify_message",
                childs: [
                    {tag: "div", cn: "nm_body",
                        childs:[
                            {tag: "div", html: "", id: "nmmessage"}
                        ]
                    },
                    {tag: "div", cn: "nm_close",
                        childs: [
                            {tag: "img", src: "img/close.gif", events: {onclick: "hideNotifyMessage()"}}
                        ]
                    }

                ]
        }



          ]
        },

        { tag: "div", cn: "cover_layer", id: "cover_layer"}



        ];





    this.getSignature = function() {

        return SYSWIDGET_WKEY+3;
    }


    this.buildWindow = function(parent) {
        this.buildDomModel(parent, this.domModel);
    }

    this.goAboutLink = function() {
        if (this.link_about != null  && this.link_about.length>0) {
            top.location = this.link_about;
        }
        else {
            this.nop();
        }
    }

    this.goBlogLink = function() {
        if (this.link_blog != null && this.link_blog.length>0) {
            top.location = this.link_blog;
        }
        else {
            this.nop();
        }
    }


    this.buildInterface = function() {


        var rect = system.getWindowRect();
        window.onresize = this.handleResize;
        this.curSquare = 1;
        this.curPage = 1;
        this.mfrom = 0;

        // tooltips layer
        this.buildDomModel(document.body, {tag:"div", cn: "tooltips", id: "tooltips"});

        system.setElementRect(this.elements["cover_layer"], rect);


        // scroller
        this.buildDomModel(this.elements["scroller"],
                        //{ tag: "a",  cn: "page_links", href: "void", events: {onclick: "searchBottom()"}, html: "Previous"}
                        {tag: "div",  id: "scroll_prev", style: {"paddingBottom" : "5px", "textAlign" : "left"},
                                    childs: [
                                        //{ tag: "img", cn:"scroll_btn",src: "img/up.gif", events: {onclick: "searchUp()"} }
                                        { tag: "a",  cn: "page_links", href: "void", events: {onclick: "searchBottom()"}, html: "Previous"},
                                    ]});
        this.elements["scroll_prev"].style.visibility = 'hidden';
        var classname= "square_off";
        for (var i = 1;  i<= this.squaresNum; i++) {

            this.buildDomModel(this.elements["scroller"],
                {tag: "div",  my_nmb: i, id: "square_"+i,  cn: classname, events: {}}
                  );
        }

        this.buildDomModel(this.elements["scroller"],
                            //{ tag: "a",  cn: "page_links",  href: "void", events: {onclick: "searchUp()"}, html: "Next"}
                                {tag: "div",  id: "scroll_next", style: {"paddingTop" : "5px", "textAlign" : "left"},
                                    childs: [
                                       // { tag: "img", cn:"scroll_btn", src: "img/down.gif", events: {onclick: "searchBottom()"} }
                                       { tag: "a", cn: "page_links", href: "void", events: {onclick: "searchUp()"}, html: "Next"},
                                    ]});
        this.elements["scroll_next"].style.visibility = 'hidden';

        this.hideElement("cover_layer");
        this.doPrecalculations();
        this.loadSettings();

        if (this.firstSearchStr.length > 0) {
            this.elements["input_search"].value = this.firstSearchStr;
            this.doSearch();
        }

    }

    this.colorSquares = function(num) {
        for (var i = 1;  i<=num; i++) {

            var classname;
            if (this.curSquare == i) {
                classname = "square_border";
            }
            else {
             classname= "square";
            }



            var el = this.elements["square_"+i];

            el.className = classname;

            this.assignEvent(el, "onclick", "scrollDo('"+i+"')");
            this.assignEvent(el, "onmouseover", "scrollMouseOver('"+i+"')");

            this.assignEvent(el, "onmouseout", "scrollMouseOut('"+i+"')");


        }
    }


    this.graySquares = function(num) {


        for (var i = 1;  i<=num; i++) {

            var classname = "square_off";
            var el = this.elements["square_"+i];


            if (el != null) {
                el.className = classname;

                this.clearEvent(el, "onclick", "");
                this.clearEvent(el, "onmouseover", "");
                this.clearEvent(el, "onmouseout", "");
            }


        }

    }


/********************************************************************************
 *
 *  Z INDEXING AND DRAG
 *
 */

    this.isFileDrag = false;
    this.maxZindex = 1000;

    this.getMaxZindex = function() {
        this.maxZindex ++;
        return this.maxZindex;
    }

    this.putElOnTop = function(el) {
        el.style.zIndex = this.getMaxZindex();
    }


    this.showCallouts = function() {

        if (isdebug) {
            console.log('show callouts begin', this.curSquare, this.topmost_cl_number);
        }
        this.ttCoords = [];
        // hide Top 5 tooltips

        var tooltips = document.getElementById('tooltips');

        for (var idx=0; idx<tooltips.childNodes.length; idx++) {
            //alert(tooltips[idx]);

            if (tooltips.childNodes[idx].style != null
                && tooltips.childNodes[idx].style.display != 'none') {

                tooltips.childNodes[idx].style.display='none';
            }
        }

        var ttCounter = 0;

        for (var i = (this.curSquare-1)*this.topmost_cl_number;
                i<(this.curSquare)*this.topmost_cl_number; i++) {
//             alert (i);
            //var el = this.elements["tt_pin_res_"+i];
            if (i<this.busyCoords.length) {

                var el = this.elements["pin_res_"+i];

                if (el.style.display == 'none') {
                    continue;
                }

                if (isdebug) {
                    console.log('show callouts: ', i);
                }
                var c = this.busyCoords[i].c;
                var tt = this.busyCoords[i].tt;



                this.ttCoords[ttCounter] = {x: c.x, y : c.y, tooltip: tt, type: null};
                ttCounter++;
            }
            else {
                break;
            }

        }

        if (this.ttCoords.length<1) {
            return;
        }



        this.markttCoords();

        for (var idx in this.ttCoords) {


            ttApplyTooltipType(this.ttCoords[idx].tooltip, this.ttCoords[idx].type, this.ttCoords[idx]);
            // check coords
            //ttApplyTooltipType(this.ttCoords[idx].tooltip, this.ttCoords[idx].type);

            ttShow(this.ttCoords[idx] , this.ttCoords[idx].tooltip);

        }
    }

/********************************************************************************
 *
 *   COMMON
 *
 */



    this.nop = function() {
        alert("Future function");
    }



/********************************************************************************
 *
 *  DISPATCHER
 *
 */


    this.dispatchMsg = function(msg) {

        if(msg.result == -1) {
            alert("Error. Check your internet connection.");
        }

        switch (msg.cmd) {

            case "get_settings_res" :

                if (isdebug) {
                    console.log("Loading settings...");
                }

                // loading settings
                if (msg.data["request_timeout"] != null) {
                    if (isdebug) {
                        console.log("request_timeout:"+msg.data["request_timeout"]);
                    }

                    // request_timeout
                    this.searchTimeoutValue = msg.data["request_timeout"]*1000  ;
                }

                if (msg.data["page_scroll_step"] != null) {

                    // request_timeout
                    this.pageScrollStep = parseInt(msg.data["page_scroll_step"]);

                    if (this.pageScrollStep % 5 != 0) {
                        this.pageScrollStep = this.pageScrollStep + (5 - (this.pageScrollStep % 5));
                    }

                    if (isdebug) {
                        console.log("page_scroll_step:"+this.pageScrollStep);
                    }
                }

                if (msg.data["topmost_cl_number"] != null) {
                    if (isdebug) {
                        console.log("topmost_cl_number:"+msg.data["topmost_cl_number"]);
                    }
                    // request_timeout
                    this.topmost_cl_number = msg.data["topmost_cl_number"];
                }


                if (msg.data["square_delay"] != null) {
                    if (isdebug) {
                        console.log("scrollOverTimeout:"+msg.data["square_delay"]);
                    }
                    // request_timeout
                    this.scrollOverTimeout = msg.data["square_delay"];
                }

                if (msg.data["link_about"] != null) {
                    if (isdebug) {
                        console.log("link_about:"+msg.data["link_about"]);
                    }
                    // request_timeout
                    this.link_about = msg.data["link_about"];
                }

                if (msg.data["link_blog"] != null) {
                    if (isdebug) {
                        console.log("link_blog:"+msg.data["link_blog"]);
                    }
                    // request_timeout
                    this.link_blog = msg.data["link_blog"];
                }

                //this.hideLayer();
            break;

            case "query_result":

                if (isdebug) {
                    console.log('msg.cmd: query_result');
                }

                if (this.searchTimeoutId>0) {

                    clearTimeout(this.searchTimeoutId);
                    this.searchTimeoutId = -1;
                }
                else {

                    if (isdebug) {
                        console.log('query_result: hideNotifyMessage()');
                    }
                    // was laready cleared,  lets close error message
                    this.hideNotifyMessage();
                }

                if (isdebug) {
                    console.log('query_result: clearing old values and results...');
                }
                // clear old results
                this.clearPrecalc();
                /*if (isdebug) {
                    console.log('query_result: this.precalc', this.precalc);
                }*/

                this.elements["main_circles"].innerHTML = '';
                this.elements["tooltips"].innerHTML = '';
                this.cur_zindex = 20;
                if (isdebug) {
                    console.log('query_result: clearing old values and results finished.');
                }



                var count = msg.results_count;

                //this.mfrom = parseInt(msg.data.length)+parseInt(from);
                this.pinsCount = parseInt(msg.data.length);



                this.elements['pages_text'].innerHTML = (this.curPage-1)*(this.pageScrollStep*3)+1+'-'+this.curPage*(this.pageScrollStep*3)+' of '+count;


                //var ttCounter = 0;
                //this.ttCoords = [];
                //this.ttCoordsBusy = [];

                if (isdebug) {
                    console.log('query_result: FOR loop begins');
                }

                this.graySquares(this.squaresNum);
                for (var i = 0; i<msg.data.length; i++) {
                    var res = msg.data[i];
                    var ses = res.ses;




                    if (isdebug) {
                        console.log('query_result: find best coords started');
                    }

                    var c_temp = this.findBestCoords(ses, i);


                    var c = {x: 0, y : 0};
                    c.x = c_temp.c.x;
                    c.y = c_temp.c.y;
                    var area_idx = c_temp.idx;



                    if (isdebug) {
                        console.log('query_result: find best coords finished ',c);
                    }

                    // not found - continue
                    if (c.x == -1 && c.y == -1) {
                        continue;
                    }

                    //alert(this.elements["img_circles"].style.offsetLeft);
                    c.x += getLeft(this.elements["img_circles"])-8;
                    c.y += getTop(this.elements["img_circles"])-20;
                    //alert(c.x+':'+c.y);

                    /*re = /(['()])/g;
                    re2 = /(&#39;)/g;
                    re3 = /(["])/g;*/

                    if (res.item.desc.substr(res.item.desc.length-4, res.item.desc.length)
                            != '<br>') {
                        res.item.desc += '<br>';

                    }

                    //  reduce name
                    if (res.item.name.length>35) {
                        res.item.name = res.item.name.substr(0,32)+'...';
                    }


                    //  reduce description
                    if (res.item.desc.length>100) {
                        res.item.desc = res.item.desc.substr(0,97)+'...<br>';
                    }

                    //  reduce url
                    if (res.item.url.length>35) {
                        item_url_short = res.item.url.substr(0,32)+'...';
                    }
                    else {
                        item_url_short = res.item.url;
                    }

                    var searcher = '';



                    searcher += '<b>' + i + '.</b>&nbsp;';


                    var first = true;
                    for (var se in ses) {
                        if (first == false) {
                            searcher += ', ';
                        }
                        else {
                            first = false;
                        }

                        if (se == 'google') {
                            searcher += '<font color=red>Google';
                        }

                        else if (se == 'yahoo') {
                            searcher += '<font color=green>Yahoo';
                        }

                        else if (se == 'msn') {
                            searcher += '<font color=blue>Bing';
                        }


                        searcher += ': ' + res.ranks[se];

                        searcher += '</font>';
                    }
                    //alert('aaaaaa');
                    //searcher += ')';


                    //res.item.desc = '<b>Killer</b> Pumpkins is the premiere halloween web site offering a unique vision of how halloween came to be. You can view scary pumpkins, chilling stories and purchase King Pumpkin items in the online store. ... KillerPumpkins. ΔΥ <b>Killer</b> "Kin" <b>Killer</b> Events. About the Artist ... Read the "<b>Killer</b> Story" and find out how the curse of the KillerPumpkins began ...';


                    var url_parts = parseUrl(res.item.url);

                    // add thumbnail
                    var pic_tmp = new Image(60,45);
                    //this.lastImageNotLoaded = false;

                    //pic_tmp.onLoad = this.imageNotLoaded;
                    pic_tmp.src= "http://open.thumbshots.org/image.pxf?url=http://"+url_parts.host;
                    //60,45


                    var tooltip = '';

                        tooltip = "<table border=0 padding=0><tr valign=top ><td colspan=2>"+searcher+"</td></tr><tr><td valign=center><img src='http://open.thumbshots.org/image.pxf?url=http://"+url_parts.host+"' width=60 height=45 /></td><td valign=top>";

                        tooltip  +=  "<a title='"+res.item.url+"' class='blue_links' href='"+res.item.url
                                      +"' target='blank'>"+res.item.name+"</a><br>"
                                      +res.item.desc
                                      +"<font color='green'>"+item_url_short+'</font>';
                        tooltip  += '</td></tr></table>';
                    //}

                    if (isdebug) {
                        console.log('query_result: tooltip created ');
                    }


                    this.buildDomModel(this.elements["main_circles"],
                    {tag: "div", id: "pin_res_"+i, my_area_idx: area_idx, style: {
                        position: "absolute",
                        left: c.x+"px",
                        top: c.y+"px",
                        width: "8px",
                        height: "18px"
                        }
                        ,  childs: [

                            {tag:"img", id: "img_pin_"+i,  src: "img/pin.gif", width: "8", height: "18"

                            }
                        ]


                    });

                    if (isdebug) {
                        console.log('query_result: buildDomModel() ');
                    }

                    // fix PIN element to precalc array

                    this.busyCoords[this.busyCoords.length-1].el = document.getElementById("img_pin_"+i);
                    this.busyCoords[this.busyCoords.length-1].c = c;

                    var tt = ttPrepare(document.getElementById("img_pin_"+i), "tt_pin_res_"+i
                        ,  tooltip
                        );

                    if (isdebug) {
                        console.log('query_result: preparedTooltip() ');
                    }

                    tt.onmousemove = this.checkPins;
                    tt.onclick = this.ttOnClick;


                    tt.parent = this;
                    this.busyCoords[this.busyCoords.length-1].tt = tt;

                    /*if (ttCounter != 100) {
                        // collect points and tooltips for 5 popups
                        if (ttCounter<this.topmost_cl_number) {
                            this.ttCoords[ttCounter] = {x: c.x, y : c.y, tooltip: tt, type: null};
                            ttCounter++;
                        }
                        else {

                            // show Top 5
                            this.showTooltips();
                            ttCounter = 100;
                        }
                    }*/


                    if (isdebug) {
                        console.log('query_result: after ttcounter ');
                    }

                }

                this.scrollDo(1);

                //////////////////////////////////////////
                // show advertisement
                //////////////////////////////////////////
                if (msg.adv != null) {

                    var res = msg.adv;
                    var ses = {google:'1', yahoo:'1', msn: '1'};

                    var c_temp = this.findBestCoords(ses, 0, true);

                    var c = {x: 0, y : 0};
                    c.x = c_temp.c.x;
                    c.y = c_temp.c.y;
                    var area_idx = c_temp.idx;

                    // not found - continue
                    if (c.x == -1 && c.y == -1) {
                        break;
                    }

                    //alert(this.elements["img_circles"].style.offsetLeft);
                    c.x += getLeft(this.elements["img_circles"])-8;
                    c.y += getTop(this.elements["img_circles"])-20;

                    //  reduce description
                    if (res.adtext.length>270) {
                        res.adtext = res.adtext.substr(0,267)+'...<br>';
                    }


                    var tooltip = '';
                        tooltip = "<table border=0 class='advertisement' width='260px' height='85px'><tr><td valign=center><img src='var/img/"
                                    +res.adimage+"' width=60 height=45 /></td><td width='90%' valign=top>";

                        if (res.adurl.length>0 && res.adtitle.length>0) {
                            tooltip  += "<a title='"+res.adurl+"' class='blue_links' href='"
                                      + res.adurl
                                      +"'  target='blank'>"+res.adtitle+"</a><br>"
                        }
                        tooltip  += res.adtext+"<br>";
                        tooltip  += "<font color='green'>"+res.adurl+'</font>'
                        tooltip  += '</td></tr></table>';

                    var i = msg.data.length;


                    this.buildDomModel(this.elements["main_circles"],
                    {tag: "div", id: "pin_res_"+i, my_area_idx: area_idx, style: {
                        position: "absolute",
                        left: c.x+"px",
                        top: c.y+"px",
                        width: "8px",
                        height: "18px"
                        }
                        ,  childs: [

                            {tag:"img", id: "img_pin_"+i,  src: "img/pin_adv.gif", width: "8", height: "18"

                            }
                        ]


                    });

                    // fix PIN element to precalc array

                    this.busyCoords[this.busyCoords.length-1].el = document.getElementById("img_pin_"+i);
                    this.busyCoords[this.busyCoords.length-1].c = c;

                    var tt = ttPrepare(document.getElementById("img_pin_"+i), "tt_pin_res_"+i
                        ,  tooltip
                        );

                    tt.onmousemove = this.checkPins;
                    tt.onclick = this.ttOnClick;


                    tt.parent = this;

                    ttApplyTooltipType(tt, ttADVRIGHT, c);
                    ttShow(c , tt);

                }

                if (this.curFilter > -1) {
                    this.filterPins(this.curFilter);

                }

                //this.elements["scroll_next"].style.display = 'block';
                this.elements["scroll_next"].style.visibility = 'visible';
                this.colorSquares(Math.ceil((this.busyCoords.length-1)/this.topmost_cl_number));
            break;

        }

        this.hideLayer();


        // todo check errors
        if(msg.error != null) {
            return;
        }
    }

    this.showTooltips = function () {

            var i=0;

            this.markttCoords();

            for (var idx in this.ttCoords) {

                ttApplyTooltipType(this.ttCoords[idx].tooltip, this.ttCoords[idx].type, this.ttCoords[idx]);
                // check coords
                //ttApplyTooltipType(this.ttCoords[idx].tooltip, this.ttCoords[idx].type);

                ttShow(this.ttCoords[idx] , this.ttCoords[idx].tooltip);

            }
    }

    this.markttCoords = function () {

        // find top
        var miny_idx = -1;
        var miny2_idx = -1;
        var miny = 10000;
        var miny2 = 10000;


        for (var idx in this.ttCoords) {

            if (this.ttCoords[idx].y<miny) {

                miny2_idx = miny_idx;
                miny_idx = idx;
                miny2 = miny;
                miny = this.ttCoords[idx].y;
            }
            else if (this.ttCoords[idx].y<miny2) {

                miny2_idx = idx;
                miny2 = this.ttCoords[idx].y;
            }
        }


        if (miny2_idx>-1 && miny_idx>-1) {
            if (this.ttCoords[miny_idx].x > this.ttCoords[miny2_idx].x) {
                this.ttCoords[miny_idx].type = ttRIGHTTOP;
                this.ttCoords[miny2_idx].type = ttLEFTTOP;
            }
            else {

                this.ttCoords[miny2_idx].type = ttRIGHTTOP;
                this.ttCoords[miny_idx].type = ttLEFTTOP;
            }
        }


        var minx = 10000;
        var minx2 = 10000;

        var minx_idx = -1;
        var minx2_idx = -1;

        for (var idx in this.ttCoords) {
            if (this.ttCoords[idx].type == null) {

                if (this.ttCoords[idx].x<minx) {

                    minx2_idx = minx_idx;
                    minx_idx = idx;
                    minx2 = minx;
                    minx = this.ttCoords[idx].x;
                }
                else if (this.ttCoords[idx].x<minx2) {

                    minx2_idx = idx;
                    minx2 = this.ttCoords[idx].x;
                }
            }
        }

        if (minx_idx != -1 && minx2_idx != -1) {
            if (this.ttCoords[minx_idx].x > this.ttCoords[minx2_idx].x) {

                this.ttCoords[minx_idx].type = ttRIGHTBOT;
                this.ttCoords[minx2_idx].type = ttLEFTBOT;
            }
            else {

                this.ttCoords[minx2_idx].type = ttRIGHTBOT;
                this.ttCoords[minx_idx].type = ttLEFTBOT;
            }
        }

        for (var idx in this.ttCoords) {
            if (this.ttCoords[idx].type == null) {
                this.ttCoords[idx].type = ttLEFTBOT;
            }
        }


        /*console.log(this.ttCoords);
        console.log(miny_idx,miny2_idx,miny,miny2);
        console.log(minx_idx,minx2_idx,minx,minx2);*/

        // find miny

    }

    this.hideTooltips = function (ttCoords) {

            var i=0;
            for (var idx in ttCoords) {
                ttCoords[idx].tooltip.style.display='none';
            }

    }

    this.checkPins = function (e){


            //alert('mousemove');
            if (ttCloseTimeoutID) {

                    clearTimeout(ttCloseTimeoutID);
                    ttCloseTimeoutID = null;
                    this.style.display = 'block';
            }

            if (ttshowTimeoutID) {

                    clearTimeout(ttshowTimeoutID);
                    ttshowTimeoutID = null;
            }


            if (this.parent.ttCoords.length<=0){
                var f = function () {

                            //alert(tt);
                            ttMouseOutTimeout(null, this);
                }


                this["onmouseout"] = f;
            }

            // if TOP5 visible
            var posx=0,posy=0;
            if(e==null) e=window.event;

            var local_coords;
            if(e.pageX || e.pageY) {
                posx=e.pageX; posy=e.pageY;
                local_coords = {x: e.layerX, y: e.layerY};
            }
            else if(e.clientX || e.clientY) {

                if(document.documentElement.scrollTop){
                    posx=e.clientX+document.documentElement.scrollLeft;
                    posy=e.clientY+document.documentElement.scrollTop;
                }
                else {
                    posx=e.clientX+document.body.scrollLeft;
                    posy=e.clientY+document.body.scrollTop;
                    }

               local_coords = {x: e.offsetX, y: e.offsetY};
            }



            /*if (this.parent.lastShown != null && this.parent.lastShown != this) {
                this.parent.lastShown.style.display = 'none';
            } */

            //alert(local_coords.y);
            if ((local_coords.y<ttTooltipTranspArea && this.ttParams && this.ttParams.transpType == 0)
                || (local_coords.y>ttTooltipTranspArea && this.ttParams && this.ttParams.transpType == 1)
                || local_coords.y<ttTooltipTranspArea) {


                for (var i =0; i<this.parent.busyCoords.length; i++) {

                        //alert(this.busyCoords.length);
                        var pin = this.parent.busyCoords[i];
                        var c2 = {x: 0, y:0 }
                        c2.x =  pin.c.x+14;
                        c2.y =  pin.c.y+14;


                        if ( (pin.c.x<=posx && pin.c.y<=posy && c2.x>=posx && c2.y>=posy)

                        ) {
                            // FOUND pin
                            //alert('Tooltip!!!');
                            //showTooltip(e,pin.el);
                            if (this.parent.lastShown != null ) {

                                //this.parent.lastShown.style.display = 'none';
                                var th = this;
                                var f = function () {
                                    th.parent.lastShown.style.display = 'none';
                                    ttCloseTimeoutID = null;
                                }
                                ttCloseTimeoutID = setTimeout(f, ttCloseTimeoutValue);

                            }

                            this.parent.lastShown = pin.el.tooltip;
                            this.parent.hideTooltips(this.parent.ttCoords);
                            this.parent.ttCoords = [];

                            ttMouseOverTimeout({x:posx,y:posy} , pin.el.tooltip, true);
                            return;
                        }

                }
            }


        }

        this.ttOnClick = function (e) {

            this.parent.cur_zindex++;
            var cur = this.parent.cur_zindex;
            this.style.zIndex = cur;

            if(this.parent.cur_zindex>1000) {
                this.parent.cur_zindex = 20;
            }
        }

}

Desktop.prototype = new Widget();
