var AJAX_SERVER_TEMPLATES = "/ajaxServer";
var divcontainerName = 'template_ajax_place';

var Pager = Class.create();
Pager.prototype = {
    initialize : function(outerContainerName, totalResult, blockObject) {
        this.browseContainer = Builder.node('div', {className : 'pager_title'}, 'Browse pages: ');
        this.browseContainer.style.display="none";
        this.blockObj = blockObject;
        this.PREVIOUS_PAGE = "Previous";
        this.NEXT_PAGE = "Next";
        this.FIRST_PAGE = "First";
        this.LAST_PAGE = "Last";
        this.from = 0;
        this.to = 0;
        this.templatesPerPage = 6;
        this.pagesLine=5;
        /*this.totalResults = totalResult;
        this.total = Math.ceil(totalResult / this.perPage);*/
        this.current = 1;
        this.outerContainerName = outerContainerName;
        this.pages = new Array();
        this.borderPages = new Array();
        this.clearing = Builder.node('div', {className: 'clearing'});
        this.first = Builder.node('div', {className : 'container'});
        this.borderFirst = Builder.node('div', {className : 'sep_div'},[this.first]);
        this.first.innerHTML = this.FIRST_PAGE;
        Event.observe(this.first, 'click', this.clickCallback.bindAsEventListener(this.first, this));

        this.last = Builder.node('div', {className : 'container'});
        this.last.innerHTML = this.LAST_PAGE;
        Event.observe(this.last, 'click', this.clickCallback.bindAsEventListener(this.last, this));

        this.previous = Builder.node('div', {className : 'container'});
        this.borderPrevious = Builder.node('div', {className : 'sep_div'},[this.previous]);
        this.previous.innerHTML = this.PREVIOUS_PAGE;
        Event.observe(this.previous, 'click', this.clickCallback.bindAsEventListener(this.previous, this));

        this.next = Builder.node('div', {className : 'container'});
        this.borderNext  = Builder.node('div', {className : 'sep_div'},[this.next]);

        this.next.innerHTML = this.NEXT_PAGE;
        Event.observe(this.next, 'click', this.clickCallback.bindAsEventListener(this.next, this));

        this.mainBlock = Builder.node('div', {className : 'all_pages'});
        this.mainBlock.appendChild(this.browseContainer);
        this.mainBlock.appendChild(this.borderFirst);
        this.mainBlock.appendChild(this.borderPrevious);

        for (var i = 0; i < this.pagesLine; i++) {
            this.pages[i] = Builder.node('div', {className : 'container'});
            this.borderPages[i] = Builder.node('div', {className : 'sep_div'},[this.pages[i]]);
            Event.observe(this.pages[i], 'click', this.clickCallback.bindAsEventListener(this.pages[i], this));
            this.mainBlock.appendChild(this.borderPages[i]);
        }

        this.mainBlock.appendChild(this.borderNext);
        this.mainBlock.appendChild(this.last)
        $(outerContainerName).appendChild(this.mainBlock);
        $(outerContainerName).appendChild(this.clearing);

    },

    recalculate : function() {        
        this.from = this.current - 2;
        this.to = this.current + 2;
        if (this.from < 0){
            this.to = (this.to - this.from) + 1;
        }
        if(this.from == 0)
            this.to++;
        if (this.to > this.total) {
            this.from -= this.to - this.total;
            this.to = this.total;
        }
        if (this.from < 1)
            this.from = 1;
    },

    clickCallback : function(event) {
        var outer = arguments[1];
        var current = 1;
        switch(this.innerHTML){
           case outer.FIRST_PAGE :{
               current = 1;
               break;
           }
           case outer.LAST_PAGE:{
               current = outer.total;
               break;
           }
           case outer.PREVIOUS_PAGE:{
               var previous = outer.current - 1;
               if(previous < 1){
                    current = 1;
               }else{
                    current = outer.current - 1;
               }                              
               break;
           }
           case outer.NEXT_PAGE:{
               var next = outer.current + 1;
               if(next > outer.total){
                    current = outer.total;
               }else{
                    current = outer.current + 1;
               }                  
               break;
           }
           default:{
               try{
                   current = parseInt(this.innerHTML);
               }catch(e){
                   outer.current = 1;
               }
           }
        }

        if(current != outer.current) {
            outer.current = current;
            outer.blockObj.synchronize(outer.current);
            outer.blockObj.parameters.currentPage = outer.current;
            outer.blockObj.updateTemplates();    
        }
    },

    redraw : function() {
        for (var i = 0; i < this.pagesLine; i++) {
            this.pages[i].innerHTML = "";
            this.borderPages[i].style.borderRight="none";
        }
        if(this.to > 1){
            this.browseContainer.style.display = "block";
            for (var i = 0, page = this.from; page <= this.to; i++ , page++) {
                this.pages[i].innerHTML = page;
                if(page < this.total){
                    this.borderPages[i].style.borderRight="1px solid";
                }
                if(page == this.current){
                    this.pages[i].style.color="#737573";
                    this.pages[i].style.fontWeight = "normal";
                    this.pages[i].style.cursor = "default";
                    this.pages[i].style.textDecoration = "none";
                }else{
                    this.pages[i].style.color="#FF9631";
                    this.pages[i].style.fontWeight = "bold";
                    this.pages[i].style.cursor = "pointer";
                    this.pages[i].style.textDecoration = "underline";
                }
             }
        }else{
            this.browseContainer.style.display = "none";
        }

        if(this.from == 1){
            this.borderFirst.style.display="none";
            this.borderPrevious.style.display="none";
        }

        if(this.from > 1){
            this.borderFirst.style.display="block";
            this.borderPrevious.style.display="block";
        }

        if(this.to == this.total){
            this.last.style.display="none";
            this.borderNext.style.display="none";
        }

        if(this.to < this.total){
            this.last.style.display="block";
            this.borderNext.style.display="block";
        }
    },

    refresh : function(){
       this.recalculate();
       this.redraw();
    },

    setTotalResult : function(totalResult){
        this.totalResults = totalResult;
        this.total = Math.ceil(totalResult / this.templatesPerPage);
        this.refresh();
    }
}

var TemplatesDegugger = Class.create();
TemplatesDegugger.prototype = {
    initialize : function() {
        try {            
            this.mainWnd = window.open(window.location, 'debug', 'left=0,top=0,width=500,height=500,toolbar=no,scrollbars=yes');
            this.mainWnd.document.write("<html><head></head><body><div id=\"mainDebugDiv\"></div></body></html>");
        } catch(e) {
            // alert(e.message);
        }
    },

    write : function(logString){
        try {
            timestampObject = new Date();
            var templatesLog = Builder.node('div');
            var timeLog = timestampObject.getHours() + ":" + timestampObject.getMinutes() + ":" + timestampObject.getSeconds();
            templatesLog.innerHTML = "<b style=\"text-color:blue;\">&nbsp;&nbsp;" + timeLog + "</b>" + logString;
            this.mainWnd.document.getElementById('mainDebugDiv').appendChild(templatesLog);
        } catch(e) {
           // alert(e.message);
        }
    },

    close : function() {
        try{
            this.mainWnd.close();
        } catch(e) {
           // alert(e.message);
        }
    }
}

var Params = Class.create();
Params.prototype = {
    initialize : function() {
        this.keyword = "";
        this.currentPage = 1;
        this.perPage = 6;
        this.categoryId = -1;
    }
}

var AjaxParameters = Class.create();
AjaxParameters.prototype = {
    initialize : function(params) {
        this.method = "getTemplates";
        this.parameters = params;
    }
}

var TemplatesBlock = Class.create();
TemplatesBlock.prototype = {
    initialize : function(block, debug) {
        this.parameters = new Params();
        if(typeof global_category_id != "undefined") {
            this.parameters.categoryId = global_category_id;
        }

        this.searchRequestParams = new AjaxParameters(this.parameters);
        this.spacer = Builder.node('div', {className : 'space_div'});
        this.pager = new Array();
        this.pager[0] = new Pager(divcontainerName, 0, this);
        this.templateBlocks = new Array();
        this.templateTable = new Array();
        this.templateCell = new Array();
        this.emptyRow = Builder.node('div', {className: 'empty_row'});
        this.noResults = Builder.node('div', {className: 'no_results', style:"display:none"}, ['Sorry no templates found']);
        this.block = block;
        this.templatesBlockDebugger = null;
        this.debug = debug;
        var abcstyles = {0:'left_cell',1:'middle_cell',2:'right_cell',3:'left_cell',4:'middle_cell',5:'right_cell'};

        for (var i = 0; i<6; i++){
            this.templateCell[i] = Builder.node('div', {className: 'template_cell'});
            this.templateTable[i] = Builder.node('div', {className : abcstyles[i]}, [
                 this.templateCell[i]
            ]);
        }
        this.mainTable = Builder.node('div', {className: 'template_table'}, [
                Builder.node('div', {className : 'columns3'}, [
                        Builder.node('div', {className : 'template_row'}, [this.templateTable[0], this.templateTable[1], this.templateTable[2]])
                        ]),
                this.emptyRow,
                Builder.node('div', {className : 'columns3'}, [
                        Builder.node('div', {className : 'template_row'}, [this.templateTable[3], this.templateTable[4], this.templateTable[5]])
                        ])                       
        ]);
        $(divcontainerName).appendChild(this.mainTable);
        $(divcontainerName).appendChild(this.spacer);
        $(divcontainerName).appendChild(this.noResults);
        if(this.debug){
            this.templatesBlockDebugger = new TemplatesDegugger();
        }
        this.pager[1] = new Pager(divcontainerName, 0, this);
        this.updateTemplates();
    },

    synchronize : function(currentParam) {
        for (var i = 0; i < this.pager.length; i++) {
            this.pager[i].current = currentParam;
        }
    },

    setTotal :function(total) {
        for (var i = 0; i < this.pager.length; i++) {
            this.pager[i].setTotalResult(total);
        }
    },

    updateTemplates : function() {
        var outer = this;
        showLoader();
        new Ajax.Request(AJAX_SERVER_TEMPLATES, {
                parameters:{"queryObject" : Object.toJSON(this.searchRequestParams)},
                method : 'post',
                onSuccess : function(t) {
                    var resultObject = t.responseText.evalJSON();
                    if (resultObject) {
                        if(!resultObject.total){
                            resultObject.total = 0;                            
                        }
                        if(!resultObject.templates){
                            resultObject.templates = new Array();
                        }
                        outer.setTotal(resultObject.total);
                        outer.templates = resultObject.templates;
                        outer.drawTemplates();
                    }
                    hideLoader();
                }
         });
    },

    drawtemplatesTimer : function(k) {
        if(this.debug){
            this.templatesBlockDebugger.write("drawtemplatesTimer " + k)
        }
        this.templateCell[k].innerHTML = "";

        if( (this.templates.length-1) >= k) {
            var link = '/templates/' + this.templates[k].titlerd + '-' + this.templates[k].id + '.html';
            var img = Builder.node('img', {src : "/image/smallPreviews/" + this.templates[k].smallSSFile});
            var linkPreview = Builder.node('a', {href : link }, ['Preview']);
            var a = Builder.node('a', { href: linkPreview });
            a.appendChild(img);
            var linkDownload = Builder.node('a', {href : this.templates[k].zipLink}, ['Download']);
            var linksDiv = Builder.node('div', {className: 'links'}, [linkPreview, '|', linkDownload]);
            this.templateCell[k].appendChild(a);
            this.templateCell[k].appendChild(linksDiv);
        }
    },

    drawTemplates : function() {
        var increment = 23;
        var start = 50;

        for (var k = 0; k < this.templateCell.length; k++) {
            start += increment;
            setTimeout('this.block.drawtemplatesTimer('+ k + ')', start);
        }
        if (this.templates.length <= 3) {
            this.emptyRow.style.display = "none";
            this.spacer.style.height = "10px";
        } else {
            this.emptyRow.style.display = "block";
            this.spacer.style.height = "20px";
        }
        
        if (this.templates.length == 0) {
            this.noResults.style.display = "block";
            this.mainTable.style.display = "none";
            this.spacer.style.display = "none";
        } else {
            this.noResults.style.display = "none";
            this.mainTable.style.display = "block";
            this.spacer.style.display = "block";
        }
    }
}

var block;

document.observe("dom:loaded", function() {
    if ($(divcontainerName) != null) {
        var debug = false;

        var currentLocation = window.location.href;
        if( currentLocation != null){        
        var arr1 = currentLocation.split("?");
            if(arr1 != null && arr1.length > 1){
                var pageArguments = arr1[1].split("&");
                for(var i = 0; i < pageArguments.length; i++){
                    var keyValueArray = pageArguments[i].split("=");
                    if(keyValueArray != null &&
                       (keyValueArray[0] != null) &&
                            (keyValueArray[1] != null)) {
                        if(keyValueArray[0] == 'debug' && keyValueArray[1] == 'true') {
                            debug = true;
                        }
                    }
                }
            }
        }

        block = new TemplatesBlock(block, debug);
        //Event.observe($("search_query_fto"), 'keydown', searchFTO.bindAsEventListener());
        //Event.observe($("search_fto_button"), 'click', searchFTO.bindAsEventListener());
    }
});

function searchFTO(event) {
    //alert((e == null) + e.type + " : " + e.key);
    if((event.type == 'click') || (event.type == 'keydown' && event.keyCode == 13)){
       var search_query = $('search_query_fto').value;
       if(block) {
           block.parameters.keyword = search_query;
           block.synchronize(1);
           block.parameters.currentPage = 1;
           block.updateTemplates();
       }
    }
}

function hideLoader(){
    var targelem = document.getElementById('loader_container');
    targelem.style.display='none';
    targelem.style.visibility='hidden';

    if (navigator.userAgent.indexOf("MSIE") != -1){
        document.getElementById('template_ajax_place').style.marginTop = 0;
    } else {
        document.getElementById('template_ajax_place').style.marginTop = 10 + 'px';
    }
    document.getElementById('template_ajax_place').style.marginBottom = 0;
}


function showLoader() {
    var targelem = document.getElementById('loader_container');

    targelem.style.display = 'block';
    targelem.style.visibility = 'visible';
    targelem.style.zIndex = 1000;
    if (navigator.userAgent.indexOf("Opera") != -1 || navigator.userAgent.indexOf("MSIE 6.0") != -1) {
        targelem.style.top = "45%";
    } else {
        targelem.style.top = "50%";
    }

}
