/// Filename: Template.js
/// Description: Corvus ClientSide Template Control
/// Copyright (C) CorvusInfo d.d. All rights reserved.
/// 2008. a.d.

Type.registerNamespace("CorvusCMS.UI");


CorvusCMS.UI.Template = function(templateString) {
    
 
    this._element = null;
    this._templateString = templateString;
    this._itemHtmlOutput = '';
    this._item = null;


    this._preRenderTemplate = null;
    this._parsedTemplate = null;
    this._phJSON = null;
    this._tmpEl = null;
    
    this._bindsItem = false;
}

CorvusCMS.UI.Template.prototype = {

    ///*****Properties section
    get_element: function() {
        return this._element;
    },

    set_element: function(value) {
        if (this._element !== value) {
            this._element = value;
        }
    },

    get_templateString: function() {
        return this._templateString;
    },

    set_templateString: function(value) {
        if (this._templateString !== value) {
            this._templateString = value;
        }
    },

    get_itemHtmlOutput: function() {
        return this._itemHtmlOutput;
    },

    get_templateDOM: function() {
        var dom = document.createElement('div');
        dom.innerHTML = this.get_templateString();
        return dom;
    },

    get_itemHtmlDOMOutput: function() {

        if (this._itemHtmlOutput && this._itemHtmlOutput != '') {

            this._tmpEl = document.createElement('div');
            this._tmpEl.innerHTML = this._itemHtmlOutput;
        }
        return this._tmpEl;
    },

    dispose_itemHtmlDOMOutput: function() {
        delete (this._tmpEl);
    },

    get_item: function() {
        return this._item;
    },

    set_item: function(value) {
        if (this._item !== value) {
            this._item = value;
        }
    },

    get_parsedTemplate: function() {
        if (this._parsedTemplate == null)
            this._parsedTemplate = this._parseTemplate();
        return this._parsedTemplate;
    },

    get_phJSON: function() {
        return this._phJSON;
    },



    ///***** Methods section *****

    ///Bind item properties to template
    ///Exceptions: Catch Repeater.Error exception thrown in template Transform function (if any)
    bindProperties: function(itemIndex) {
        this._phJSON = this._getTemplateJSONs(this.get_parsedTemplate())
        var currentJSON = null;
        var propertyFinalValue = null;
        this._itemHtmlOutput = this._preRenderTemplate;

        for (var i = 0; i < this.get_phJSON().length; i++) {
            currentJSON = this.get_phJSON()[i];
//            try {

                propertyFinalValue = currentJSON.Transformation != null ? currentJSON.Transformation(this._formatValue(this._getPropertyValue(this.get_item(), currentJSON.Property), currentJSON.Format), this.get_item(), itemIndex) : this._formatValue(this._getPropertyValue(this.get_item(), currentJSON.Property), currentJSON.Format);
//            }
//            catch (e) {
//                alert('[Template.Error] :: ' + e.message);
//            }

            this._itemHtmlOutput = this._itemHtmlOutput.replace('////' + currentJSON.index + '////', propertyFinalValue);
        }
    },

    ///*** Render item in template and apply it to container element
    ///*** Parameters:
    /// > item - item to bind
    /// > elementToRenderIn - container element where template should be applied to
    /// > itemIndex - repeater itemIndex used in collections binding (optional)
    /// > parentId - parent element id used for unique naming of template markup elements(optional)
    renderHtmlInElement: function(item, elementToRenderIn, itemIndex, parentId) {
        this.set_element(elementToRenderIn);
        this.set_item(item);
        if (this.get_item() == null) {

            var templateDOM = this.get_templateDOM();
            while (templateDOM.childNodes.length)
                this.get_element().appendChild(templateDOM.childNodes[0]);

            return;
        }

        this.bindProperties(itemIndex);

        if (parentId) {
            var namedObject = this._applyNaming(this.get_itemHtmlDOMOutput(), itemIndex, parentId);
            if (namedObject)
            //this._itemHtmlOutput = namedObject.innerHTML;

                while (namedObject.childNodes.length)
                this.get_element().appendChild(namedObject.childNodes[0]);
        }


        // this.get_element().innerHTML += this._itemHtmlOutput;

        //this.dispose_itemHtmlDOMOutput();
    },

    ///*** Returns DOM element that contains markup built by template (without appending it to any element)
    ///*** Parameters:
    /// > item - item to bind
    /// > itemIndex - item index in control, collection, whereever...
    /// > parentId - parent element id used for unique naming of template markup elements(optional)
    getHtmlForItem: function(item, itemIndex, parentId) {
        this.set_item(item);
        if (this.get_item() == null)
            return this._applyNaming(this.get_templateDOM(), itemIndex, parentId).firstChild;

        this.bindProperties(itemIndex);

        if (itemIndex || parentId) {
            var namedObject = this._applyNaming(this.get_itemHtmlDOMOutput(), itemIndex, parentId);
            if (namedObject)
                this._itemHtmlOutput = namedObject.innerHTML;
        }

        return this.get_itemHtmlDOMOutput();
    },

    getOutputAsString: function(item, itemIndex) {
        this.set_item(item);
        this.bindProperties(itemIndex);
        return this._itemHtmlOutput;
    },

    equals: function(template) {
        return this.get_templateString() == template.get_templateString();
    },

    ///*** Returns: JSONs for every Property in Template
    ///*** Propery JSON contains:
    /// - Propery - property name
    /// - Format - format which property should be transformed into (optional)
    /// - Transformation - transformation function that should be applied to property value before rendering template (optional)
    _getTemplateJSONs: function(tempArr) {
        var JSONelement = null;
        var tJSONs = new Array();
        this._preRenderTemplate = this.get_templateString();

        if (tempArr)
            for (var i = 0; i < tempArr.length; i++) {
            //remove starting '[' and ending ']' and eval JSON
            var x = '';
            x = tempArr[i].substring(1, tempArr[i].length - 1);
            JSONelement = eval('(' + x + ')');
            if (JSONelement.Transformation)
                eval('(JSONelement.Transformation = ' + JSONelement.Transformation + ')');
            JSONelement.index = i;
            this._preRenderTemplate = this._preRenderTemplate.replace(tempArr[i], '////' + i + '////');
            tJSONs.push(JSONelement);
        }
        return tJSONs;
    },

    ///*** Appends element name in format: 'containerName_elementName_elementIndex' for unique identifying later
    _applyNaming: function(el, itemIndex, parentId) {
        if (!el)
            return;

        if (!itemIndex)
            itemIndex = 0;

        if (el.childNodes) {
            for (var i = 0; i < el.childNodes.length; i++) {
                this._applyNaming(el.childNodes[i], itemIndex, parentId);
            }
        }
        if (el.id && el.id != '') {
            var tmpId = el.id;
            el.id = '';
            el.id += parentId != null ? parentId.toString() + '_' : '_';
            el.id += tmpId != null ? tmpId + '_' : '_'
            el.id += itemIndex != null ? itemIndex.toString() : '';
        }
        return el;
    },

    ///Parse raw template string for later use
    ///Expensive method, use get_parsedTemplate() property instead!
    _parseTemplate: function() {
        return this.get_templateString().match(/[\[{].*?[}\\]]/g);
    },

    ///Allow Object.Property notation in template
    _getPropertyValue: function(item, property) {
        var list = property.split('.');

        for (var elem = 0; elem < list.length; elem++) {
            if (typeof (elem) == "function")
                continue;
                
            if (item[list[elem]] == null)
                return "";
            item = item[list[elem]];
        }

        return item;
    },

    _formatValue: function(value, formatString) {

        if (formatString)
            if (value.localeFormat)
            return value.localeFormat(formatString);

        return value;
    }
}

///***** Static methods section

///*** Convert HTML string to DOM element
///*** Returns: DOM element containing given string as innerHTML
CorvusCMS.UI.Template.ConvertToDOM = function(stringHTML)
{
    var dom = document.createElement('div');
    dom.innerHTML = stringHTML;
    return dom;
}

///***
CorvusCMS.UI.Template.PagerTemplateHtml = {

    Classic: function(propertyValue, pagedList) {
        var sb = new Sys.StringBuilder();
        if (pagedList.CurrentPage > 1) {
            sb.append('<a href="javascript:void(0);" cName=\"pageChange\" cArg=\"');
            sb.append((pagedList.CurrentPage - 1).toString());
            sb.append('\">Prev</a>');
        }
        sb.append(' | ');
        sb.append('<b>');
        sb.append(pagedList.CurrentPage.toString());
        sb.append('</b>');
        sb.append(' | ');

        if (pagedList.CurrentPage < pagedList.NumberOfPages) {
            sb.append('<a href="javascript:void(0);" cName=\"pageChange\" cArg=\"');
            sb.append((pagedList.CurrentPage + 1).toString());
            sb.append('\">Next</a>');
        }

        return sb.toString();
    },

    ImagePicker: function(propertyValue, pagedList) {

        var sb = new Sys.StringBuilder();

        if (pagedList.CurrentPage > 1) {
            sb.append('<img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerFirstPageIcon.png" cName=\"firstPage\" cArg=\"1\" class=\"firstPageIcon\" />');
            sb.append('<img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerPrevPageIcon.png" cName=\"prevPage\" class=\"prevPageIcon\" />');
        }
        else {
            sb.append('<img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerFirstPageIconD.png" class=\"firstPageIconD\" />');
            sb.append('<img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerPrevPageIconD.png" class=\"prevPageIconD\" />');
        }

        if (pagedList.CurrentPage < pagedList.NumberOfPages) {
            sb.append('<img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerLastPageIcon.png" cName=\"lastPage\" class=\"lastPageIcon\" />');
            sb.append('<img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerNextPageIcon.png" cName=\"nextPage\" class=\"nextPageIcon\" />');
        }
        else {
            sb.append('<img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerLastPageIconD.png" class=\"lastPageIconD\" />');
            sb.append('<img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerNextPageIconD.png" class=\"nextPageIconD\" />');
        }

        sb.append('<img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerPagerSeparator.gif" class="pagerSeparator" style="float:left;" />');
        sb.append('<img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerPagerSeparator.gif" class="pagerSeparator" style="float:right;" />');
        sb.append('Stranica ');
        sb.append(' <b>' + pagedList.CurrentPage + '</b>');
        sb.append(' / ');
        sb.append(' <b>' + pagedList.NumberOfPages + '</b>');

        return sb.toString();
    },

    DocumentPicker: function(propertyValue, pagedList) {

        var sb = new Sys.StringBuilder();

        if (pagedList.CurrentPage > 1) {
            sb.append('<img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerFirstPageIcon.png" cName=\"firstPage\" cArg=\"1\" class=\"firstPageIcon\" />');
            sb.append('<img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerPrevPageIcon.png" cName=\"prevPage\" class=\"prevPageIcon\" />');
        }
        else {
            sb.append('<img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerFirstPageIconD.png" class=\"firstPageIconD\" />');
            sb.append('<img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerPrevPageIconD.png" class=\"prevPageIconD\" />');
        }

        if (pagedList.CurrentPage < pagedList.NumberOfPages) {
            sb.append('<img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerLastPageIcon.png" cName=\"lastPage\" class=\"lastPageIcon\" />');
            sb.append('<img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerNextPageIcon.png" cName=\"nextPage\" class=\"nextPageIcon\" />');
        }
        else {
            sb.append('<img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerLastPageIconD.png" class=\"lastPageIconD\" />');
            sb.append('<img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerNextPageIconD.png" class=\"nextPageIconD\" />');
        }

        sb.append('<img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerPagerSeparator.gif" class="pagerSeparator" style="float:left;" />');
        sb.append('<img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerPagerSeparator.gif" class="pagerSeparator" style="float:right;" />');
        sb.append(' <b>' + pagedList.CurrentPage + '</b>');
        sb.append(' / ');
        sb.append(' <b>' + pagedList.NumberOfPages + '</b>');

        return sb.toString();
    },

    ImageCollection: function(propertyValue, pagedList) {

        var sb = new Sys.StringBuilder();

        if (pagedList.CurrentPage > 1) {
            sb.append('<div style="position: absolute; left: 0px; top: 0px; width:20px; z-index: 90;"><img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerPrevPageIcon.png" cName=\"prevPage\" class=\"prevPageIcon\" /></div>');
        }
        else {
            sb.append('<div style="position: absolute; left: 0px; top: 0px; width:20px; z-index: 90;"><img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerPrevPageIconD.png" class=\"prevPageIconD\" /></div>');
        }

        if (pagedList.CurrentPage < pagedList.NumberOfPages) {
            sb.append('<div style="position: absolute; right: 0px; top: 0px; width:20px; z-index: 90;"><img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerNextPageIcon.png" cName=\"nextPage\" class=\"nextPageIcon\" /></div>');
        }
        else {
            sb.append('<div style="position: absolute; right: 0px; top: 0px; width:20px; z-index: 90;"><img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerNextPageIconD.png" class=\"nextPageIconD\" /></div>');
        }


        sb.append('<div style="position: absolute; top:0; width:100%; text-align:center; z-index: 10;"> <b>' + pagedList.CurrentPage + '</b>');
        sb.append(' / ');
        sb.append(' <b>' + pagedList.NumberOfPages + '</b></div>');

        return sb.toString();
    },

    SimpleBottomPager: function(propertyValue, pagedList) {

        var sb = new Sys.StringBuilder();

        if (pagedList.CurrentPage > 1) {
            sb.append('<div style="position: absolute; left: 4px; bottom: 4px; width:20px; z-index: 100;"><img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerPrevPageIcon.png" cName=\"prevPage\" class=\"prevPageIcon\" /></div>');
        }
        else {
            sb.append('<div style="position: absolute; left: 4px; bottom: 4px; width:20px; z-index: 100;"><img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerPrevPageIconD.png" class=\"prevPageIconD\" /></div>');
        }

        if (pagedList.CurrentPage < pagedList.NumberOfPages) {
            sb.append('<div style="position: absolute; right: 4px; bottom: 4px; width:20px; z-index: 100;"><img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerNextPageIcon.png" cName=\"nextPage\" class=\"nextPageIcon\" /></div>');
        }
        else {
            sb.append('<div style="position: absolute; right: 4px; bottom: 4px; width:20px; z-index: 100;"><img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerNextPageIconD.png" class=\"nextPageIconD\" /></div>');
        }


        sb.append('<div style="position: absolute; bottom: 4px; width:100%; text-align:center; z-index: 10;"> <b>' + pagedList.CurrentPage + '</b>');
        sb.append(' / ');
        sb.append(' <b>' + pagedList.NumberOfPages + '</b></div>');

        return sb.toString();
    },

    SimpleTopPager: function(propertyValue, pagedList) {

        var sb = new Sys.StringBuilder();

        if (pagedList.CurrentPage > 1) {
            sb.append('<div style="position: absolute; left: 0px; top: 0px; width:20px; z-index: 100;"><img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerPrevPageIcon.png" cName=\"prevPage\" class=\"prevPageIcon\" /></div>');
        }
        else {
            sb.append('<div style="position: absolute; left: 0px; top: 0px; width:20px; z-index: 100;"><img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerPrevPageIconD.png" class=\"prevPageIconD\" /></div>');
        }

        if (pagedList.CurrentPage < pagedList.NumberOfPages) {
            sb.append('<div style="position: absolute; right: 0px; top: 0px; width:20px; z-index: 100;"><img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerNextPageIcon.png" cName=\"nextPage\" class=\"nextPageIcon\" /></div>');
        }
        else {
            sb.append('<div style="position: absolute; right: 0px; top: 0px; width:20px; z-index: 100;"><img src="' + httpRoot + 'CorvusCMS/img/v4/Pickers/imagePickerNextPageIconD.png" class=\"nextPageIconD\" /></div>');
        }


        sb.append('<div style="position: absolute; top:0; width:100%; text-align:center; z-index: 10;"> <b>' + pagedList.CurrentPage + '</b>');
        sb.append(' / ');
        sb.append(' <b>' + pagedList.NumberOfPages + '</b></div>');

        return sb.toString();
    }
}
CorvusCMS.UI.Template.registerClass('CorvusCMS.UI.Template');

///Factory methods section

///***Factory object that accepts template string as parameter
///***Returns: CorvusCMS.UI.Template instance
CorvusCMS.UI.TemplateFactory = {

    createTemplateFromString : function(templateString, templateType)
    {
        return new CorvusCMS.UI.Template(templateString, templateType);
    },
    
    createTemplateFromDOM : function(elementDOM, templateType)
    {
        return new CorvusCMS.UI.Template(elementDOM.innerHTML, templateType);
    }
 
}
///***** Template class END *****


///****** Template Type Enumeration START ******/
CorvusCMS.UI.TemplateType = function () {

}

CorvusCMS.UI.TemplateType.prototype = {

    HeaderTemplate : 1,
    ItemTemplate : 2,
    SeparatorTemplate : 3,
    FooterTemplate : 4,
    PagingTemplate : 5,
    PaddingTemplate : 6
}

CorvusCMS.UI.TemplateType.registerEnum('CorvusCMS.UI.TemplateType');

///****** Template Type Enumeration END ******/

if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();