jQuery.motiveModul = ({

    globalOptions: {},
    
    motiveModel: ({
    
        getMotiveCategoryList: function(){            
			var catList = [];
            
            $.ajax({
                url: '/Motives/MotiveBox/GetMotiveCategories',
                type: 'POST',
                dataType: 'json',
                data: "",
                contentType: 'application/json; charset=utf-8',
                async: false,
                success: function(data){
                    catList = data;
                },
                error: function(objRequest){					
                    jQuery.log.error($.core.getTextResourceByKey("ERROR_CATEGORIE_MOTIVE", 
					$.motiveModul.globalOptions.textResourceList), objRequest);
                }
            });
            
            return catList;
        },
        
        motiveImageList: null,
        getMotivImageList: function(){
        	
            //If motiveImageList is empty, so connection server
            if ($.motiveModul.motiveModel.motiveImageList == null) {
                $.motiveModul.motiveModel.motiveImageList = [];
                
                $.ajax({
                    url: '/Motives/MotiveBox/GetMotives',
                    type: 'POST',
                    dataType: 'json',
                    data: "",
                    contentType: 'application/json; charset=utf-8',
                    async: false,
                    success: function(data){
                        $.motiveModul.motiveModel.motiveImageList = data;
                    },
                    error: function(objRequest){
                        jQuery.log.error($.core.getTextResourceByKey("ERROR_MOTIVE", 
					$.motiveModul.globalOptions.textResourceList), objRequest);						
                    }
                });
                
                return $.motiveModul.motiveModel.motiveImageList;
            }
            else {
                return $.motiveModul.motiveModel.motiveImageList;
            }
        }   
    
    }),
    
    motiveController: ({
    
        isInitRender: true,
        isInitRenderByCat: false,
        
        _init: function(settings){
            $.extend($.motiveModul.globalOptions, settings);
            
            
            $.motiveModul.motiveController.renderMotiveCategoryItem(settings.categorySelectBox, settings.motiveImageBox);
            
            $.motiveModul.motiveController.renderMotiveImages(settings.motiveImageBox, 0, $.motiveModul.globalOptions.countOnPage);
            $.motiveModul.motiveView.showPaping($.motiveModul.motiveModel.getMotivImageList().length, $.motiveModul.globalOptions.countOnPage);
        },
        
        /***
         * Vraci celkovy pocet obrazku motivu pro danou kategorii
         *
         * @param {String} catCadoe - kod kategorie motivu
         */
        motiveImageListByCatCode: null,
        setMotiveImageListByCatCode: function(catCode){
            var count = 0
            $.motiveModul.motiveController.motiveImageListByCatCode = [];
            $.each($.motiveModul.motiveModel.getMotivImageList(), function(index, values){
                if (values.catCode == catCode) 
                    $.motiveModul.motiveController.motiveImageListByCatCode.push(values);
            });
            
            return $.motiveModul.motiveController.motiveImageListByCatCode.length;
        },
        
        // Pole zaskrtnutych motivu
        motiveImageCheckedList: [],
        
        /**
         * Metoda vraci item option s categoriema
         * do value se vlozi catCode - motive categorie kod
         * a do name - nazev kategorie
         */
        renderMotiveCategoryItem: function(el, elTo){
            $.motiveModul.motiveView.setMotiveCategory($.motiveModul.motiveModel.getMotiveCategoryList(), el, elTo, $.motiveModul.motiveController.motiveCategoryOnChange);
        },
        
        /**
         * Vykresleni motovu pri nacteni stranky
         * Vykresli se cela skupina motivu bez ohlednu na kategorii
         */
        renderMotiveImages: function(el, from, to){
            var motiveImageList = $.motiveModul.motiveModel.getMotivImageList();
            
            for (var i = from; i < to; i++) {
                if ($.motiveModul.motiveController.isMotiveImageCheckedList($.format('#{0}_{1}', motiveImageList[i].catCode, motiveImageList[i].code))) 
                    $.motiveModul.motiveView.displayMotiveImage($(el), motiveImageList[i].code, motiveImageList[i].name, motiveImageList[i].catCode, motiveImageList[i].catName, 'checked=checked', $.format('style=\"background-color: {0};\"', $.motiveModul.globalOptions.backgroundAfterCheckImage), $.motiveModul.motiveController.imageMotiveOnClick);
                else 
                    $.motiveModul.motiveView.displayMotiveImage($(el), motiveImageList[i].code, motiveImageList[i].name, motiveImageList[i].catCode, motiveImageList[i].catName, '', '', $.motiveModul.motiveController.imageMotiveOnClick);
            }
        },
        
        /***
         * Metoda vyrenderuje obrazky motivu po vyberu kategorie
         * v select boxu.
         * @param {String} catCode - motive kategorie kod
         * @param {Object} el
         */
        renderMotiveImagesByCatCode: function(el, from, to){
            
			if (el.length) {
                $(el).children().detach();
                
                var motiveImageList = $.motiveModul.motiveController.motiveImageListByCatCode;
                
                for (var i = from; i < to; i++) {
                    if ($.motiveModul.motiveController.isMotiveImageCheckedList($.format('#{0}_{1}', motiveImageList[i].catCode, motiveImageList[i].code))) 
                        $.motiveModul.motiveView.displayMotiveImage($(el), motiveImageList[i].code, motiveImageList[i].name, motiveImageList[i].catCode, motiveImageList[i].catName,'checked=checked', $.format('style=\"background-color: {0};\"', $.motiveModul.globalOptions.backgroundAfterCheckImage), $.motiveModul.motiveController.imageMotiveOnClick);
                    else 
                        $.motiveModul.motiveView.displayMotiveImage($(el), motiveImageList[i].code, motiveImageList[i].name, motiveImageList[i].catCode, motiveImageList[i].catName, '', '', $.motiveModul.motiveController.imageMotiveOnClick);
                }
                
            }
            else {
				jQuery.log.error("Metoda: renderMotiveImagesByCatCode(),"+$.core.getTextResourceByKey("ERROR_RENDER_MOTIVE_IMAGES", $.motiveModul.globalOptions.textResourceList), "");             
            }		
            
        },
        
        /***
         * Handler onChange select box
         * @param {Object} e - event data
         */
        motiveCategoryOnChange: function(e){
            var catCode = $(this).find('option:selected').val();
            
            // Display paping - Set show Paping
            $.motiveModul.motiveController.isInit = false;
            
            if (catCode == 'ALL') {
                $.motiveModul.motiveController.isInitRenderByCat = false;
                $.motiveModul.motiveView.showPaping($.motiveModul.motiveModel.getMotivImageList().length, $.motiveModul.globalOptions.countOnPage);
            }
            else {
                $.motiveModul.motiveController.isInitRenderByCat = true;
                $.motiveModul.motiveView.showPaping($.motiveModul.motiveController.setMotiveImageListByCatCode(catCode), $.motiveModul.globalOptions.countOnPage);
            }          
           
        },
        
        
        /***
         * Metoda prida do pole {motiveImageCheckedList}
         * kod motivu pro pozdejsi overeni zda na dany motiv bylo kliknuto
         * @param {String} motiveCode - kod motivu #catCode_motiveCode
         */
        addToMotiveImageCheckedList: function(motiveCode){
            $.motiveModul.motiveController.motiveImageCheckedList.push(motiveCode);
            jQuery.unique($.motiveModul.motiveController.motiveImageCheckedList);
        },
        
        /***
         * Metoda odebere z pole {motiveImageCheckedList} zaznam.
         *
         * @param {String} motiveCode - kod motivu #catCode_motiveCode
         */
        removeOfMotiveImageCheckedList: function(motiveCode){
            if ($.inArray(motiveCode, $.motiveModul.motiveController.motiveImageCheckedList) != -1) {
            
                $.motiveModul.motiveController.motiveImageCheckedList = jQuery.grep($.motiveModul.motiveController.motiveImageCheckedList, function(val){
                    return val != motiveCode;
                });
            }
        },
        
        isMotiveImageCheckedList: function(motiveCode){
            if ($.inArray(motiveCode, $.motiveModul.motiveController.motiveImageCheckedList) != -1) {
                return true;
            }
        },
        
		/**
		 * Metoda se zavola po kliknuti na motiv. Metoda provede zmenu statusu u motivu
		 * a zaroven prida do pole {addToMotiveImageCheckedList} CatCode_MotiveCode pro pozdejsi overeni
		 * zda bylo na motiv kliknuto.
		 * @param {Object} event
		 */
        imageMotiveOnClick: function(event){
            var $el = $(event.target).parent();
            if (event.target.childElementCount > 0) 
                $el = $(event.target);
            
            var elInput = $el.find(' > input[name="motive"]');
			var elHiddenInput = $el.find(' > input[type="hidden"][name="motive-hidden"]');
            var motiveCode = $el.find(' > strong').text();
            
            if (elInput.is(':checked')) {
                $.motiveModul.motiveView.changeMotiveImageStatus($el, elInput, true);
                // Pridat do pole zaskrtle motivy
                $.motiveModul.motiveController.removeOfMotiveImageCheckedList($(elHiddenInput).val());
            }
            else {
                $.motiveModul.motiveView.changeMotiveImageStatus($el, elInput, false);
                // Odebere motiv z pole
                $.motiveModul.motiveController.addToMotiveImageCheckedList($(elHiddenInput).val());
            }
        },
        
        imagePageselectCallback: function(page_index, jq, el){
            var el = $('#motives-gallery-box');
            
            if ($.motiveModul.motiveController.isInitRender) 
                return ($.motiveModul.motiveController.isInitRender = false);
            
            el.children().detach();
            
            // Get number of elements per pagionation page from form
            var items_per_page = $.motiveModul.globalOptions.countOnPage;
            
            // Iterate through a selection of the content and build an HTML string
            
            //for (var i = page_index * items_per_page; i < max_elem; i++) {				
            if (!$.motiveModul.motiveController.isInitRenderByCat) {
                var max_elem = Math.min((page_index + 1) * items_per_page, $.motiveModul.motiveModel.getMotivImageList().length);
                $.motiveModul.motiveController.renderMotiveImages(el, (page_index * items_per_page), max_elem);
            }
            else {
                var max_elem = Math.min((page_index + 1) * items_per_page, $.motiveModul.motiveController.motiveImageListByCatCode.length);
                $.motiveModul.motiveController.renderMotiveImagesByCatCode(el, (page_index * items_per_page), max_elem);
            }
            //var motiveList = $.motiveModul.motiveModel.getMotivImageList();				
            //$.motiveModul.motiveView.displayMotiveImage($('#motives-gallery-box'), motiveList[i].code, motiveList[i].name, motiveList[i].catCode, '', '', $.motiveModul.motiveController.imageMotiveOnClick);				
            //}
            
            // Prevent click event propagation
            return false;
            
        },
        
        /**
         * Vraci vysledny vyber motivu uzivatele
         */
        getSlectedMotiveImage: function(){
            return $.motiveModul.motiveController.motiveImageCheckedList.join(';');
        },
        
        /***
         * Zrusi vyber a vycisti ulozene motivy.
         */           
    	destory: function() {
    		$.motiveModul.motiveController.motiveImageCheckedList = [];
    		$.motiveModul.motiveView.unCheckedMotivies();
    	}
    }),
    
    motiveView: ({
        /*
         * Template for generate image-box
         */
        templateMotiveImage: "<div class=\"motive-image\" {4} >" +
        "<img src=\"{5}{0}.jpg\" title=\"{9} {6}, {8} {1}\" alt=\"{9} {6}, {8} {1}\" /><br />" +
        "<input type=\"checkbox\" name=\"motive\" {3} /> <strong>{7}#{0}</strong>" +
		"<input type=\"hidden\" name=\"motive-hidden\" value=\"#{2}_{0}\" />" +
        "</div><!-- end motive-image -->" +
        "<div class=\"space\">&nbsp;</div>",
        
        unCheckedMotivies: function() {
        	$('div#motives-gallery-box .motive-image').find("input[type='checkbox']").attr('checked', false);
        },
        
        /**
         * Zobrazi na strance motivy pri prvnim nacteni stranky.
         * Take motivu priradi evnet click.
         *
         * @param {Selector} el - odkaz na image box
         * @param {String} code - kod motivu
         * @param {String} name - nazev motivu
         * @param {String} catCode - kod kategorie
         * @param {Boolean} checked - zaskrtly motiv
         * @param {String} background - pozadi za obrazkem.
         */
        displayMotiveImage: function(el, code, name, catCode, catName, checked, background, controllerName){
					
			
            el.append($.format($.motiveModul.motiveView.templateMotiveImage, 
			code, name, catCode, checked, background, 
			$.motiveModul.globalOptions.motiveFolder, catName,
			$.core.getTextResourceByKey("TEMPLATE_MOTIVE_IMAGEBOX_KOD", $.motiveModul.globalOptions.textResourceList),
			$.core.getTextResourceByKey("TEMPLATE_MOTIVE_IMAGEBOX_TITLE_MOTIVENAME", $.motiveModul.globalOptions.textResourceList),
			$.core.getTextResourceByKey("TEMPLATE_MOTIVE_IMAGEBOX_TITLE_CATEGORYNAME", $.motiveModul.globalOptions.textResourceList)))
			.live('click', function(event){                
				controllerName(event);
                event.stopImmediatePropagation();
                return false;
            });
			
            $.motiveModul.motiveView.positionMotiveImage(el);
        },
        
        /***
         * Pokud je obrazek mensi nez rodicovsky box tak ho vycentruje.
         * REV - pridat do template style a rovnout to tam pocitat.
         * @param {Object} el
         */
        positionMotiveImage: function(el){
        
            if ($.motiveModul.globalOptions.motiveImageCenter) {
                var motiveImage = el.find('div.motive-image > img').last();
                var motiveImageWidth = parseInt(motiveImage.attr('width') + 1);
                var parentWidth = parseInt(motiveImage.parent().width() - 11);
                
                if (parseInt(motiveImageWidth) < parseInt(parentWidth)) {
                    motiveImage.css({
                        'margin-left': parseInt((parentWidth) - (motiveImageWidth)) / 2 + 'px'
                    });
                }
            }
            
        },
        
        showPaping: function(totalCount, itemsPerPage){
            // Create pagination for images
            //num_entries = el.find.length;
            $("#ImagePagination").pagination(totalCount, {
                callback: $.motiveModul.motiveController.imagePageselectCallback,
                items_per_page: itemsPerPage // Show only one item per page
            });
        },
        
        
        
        /**
         * Zmena pozadi obrazku a zaskrtnuti/odskrtnuti po kliknu na motiv
         */
        changeMotiveImageStatus: function(el, elInput, checked){        	
            if (checked) {				
                elInput.attr('checked', false);
                el.css({
                    'backgroundColor': $.motiveModul.globalOptions.backgroundAfterUnCheckImage
                });
            }
            else {				
                elInput.attr('checked', true);
                el.css({
                    'backgroundColor': $.motiveModul.globalOptions.backgroundAfterCheckImage
                });
            }
        },
        
        setMotiveCategory: function(motiveCategoryItem, el, toEl, controllerName){
        
            el.children().detach();
            el.append('<option value="ALL" selected="selected">-- Vybrat kategorii --</option>');
            $.each(motiveCategoryItem, function(index, values){
                el.append('<option value="' + values.code + '">' + values.name + '</option>');
            });
            
            el.live('change', {
                to: toEl
            }, controllerName);
        }
        
        
    }),
    
    runMotiveModul: function(settings){
        $.motiveModul.motiveController._init(settings);
    }
    
});
/**********************************************************/
/********************** FONTS MODUL ***********************/
/**********************************************************/
jQuery.fontsModul = ({

    gloablOptions: {},
    
    fontsModel: ({
    	
		fontList: null,
        getFontList: function(){
            var fontList = [];
            if ($.fontsModul.fontsModel.fontList == null) {
				$.fontsModul.fontsModel.fontList = [];
				
				$.ajax({
					url: '/Motives/MotiveBox/GetFontTypes',
					type: 'POST',
					dataType: 'json',
					data: "",
					contentType: 'application/json; charset=utf-8',
					async: false,
					success: function(data){
						$.fontsModul.fontsModel.fontList = data;
					},
					error: function(objRequest){												
						jQuery.log.error($.core.getTextResourceByKey("ERROR_FONTTYPE", $.fontsModul.gloablOptions.textResourceList), objRequest);
					}
				});
				
				return $.fontsModul.fontsModel.fontList;
			} else {
			
				return $.fontsModul.fontsModel.fontList;
			}
        }
        
    }),
    /*======= FONTS  FONTS CONTROLLER ======*/
    fontsController: ({    	
    	_textObjectNum: 1,
    	
        _init: function(settings){
            $.extend($.fontsModul.gloablOptions, settings);
            
            $.fontsModul.fontsController.renderFontTypes(settings.fontTypeSelectBox, $.fontsModul.fontsModel.getFontList());
            
            settings.customerText.bind('keyup', $.fontsModul.fontsController.updateResultText);
            
            settings.linkAddTextObjectToTable.unbind('click', $.fontsModul.fontsController.addTextObjectToTable);
            settings.linkAddTextObjectToTable.bind('click', $.fontsModul.fontsController.addTextObjectToTable);
        },
        
        /***
         * Pole s textObjects kam se ukladani pridane texty
         * pro pozdejsi editaci ulozenych hodnot v tabulce.
         *
         * Key - #TEXT_NUM, VALUE - objectText {nameName, fontObjects, resultText}
         */
        textObjects: [],
        
        fontOptions: ({
            code: '',
            name: '',
            srcTTF: '',
            srcEOT: '',
            srcWOFF: '',
            srcSVG: '',
        }),
        /**
         * Updatuje vysledny text.
         * @param {Object} event
         */
        isSetHead: [],
        updateResultText: function(event){
        
            if (event.type != 'change') {
                var customerText = $(this).val();
                $.fontsModul.fontsView.setResultText($.fontsModul.fontsController.fontOptions, customerText);
            }
            else {
                var fontCode = $(this).find('option:selected').val();
                var fontName = $(this).find('option:selected').text();
                
                $.fontsModul.fontsController.fontOptions = {
                    code: fontCode,
                    name: fontName,
                    srcTTF: ($.format("{0}{1}.ttf", $.fontsModul.gloablOptions.fontFolder, $(this).find('option:selected').val())),
                    srcEOT: ($.format("{0}{1}.eot", $.fontsModul.gloablOptions.fontFolder, $(this).find('option:selected').val())),
                    srcWOFF: ($.format("{0}{1}.woff", $.fontsModul.gloablOptions.fontFolder, $(this).find('option:selected').val())),
                    srcSVG: ($.format("{0}{1}.svg", $.fontsModul.gloablOptions.fontFolder, $(this).find('option:selected').val()))
                }
                
                
                if (jQuery.inArray(fontCode, $.fontsModul.fontsController.isSetHead) == -1) {
                    $.fontsModul.fontsController.isSetHead.push(fontCode);
                    $.fontsModul.fontsView.setFontFaceToHead($.fontsModul.fontsController.fontOptions);
                }
                
                
                $.fontsModul.fontsView.setResultText($.fontsModul.fontsController.fontOptions, null);
                $.fontsModul.fontsView.displayStaticFontImage($.fontsModul.fontsController.fontOptions);
            }
        },
        
        /***
         * Preda view data pro vykresleni typu fontu select boxu
         * @param {Object} el
         * @param {Object} fontTypeList
         */
        renderFontTypes: function(el, fontTypeList){
            $.fontsModul.fontsView.setFontTypesSelectBox(el, fontTypeList, $.fontsModul.fontsController.updateResultText);
        },
        
        /***
         * Prida uzivatelsky object do tabulky pro pozdejsi editaci
         * @param {Object} event
         */
        addTextObjectToTable: function(event){
            var objName = $.fontsModul.gloablOptions.objectName.val();
            var resultText = $.fontsModul.gloablOptions.resultText.text();
            //resultText.trim()
            if ($.trim(resultText) != '' &&
            $.fontsModul.fontsController.isSetHead.length != 0) {
                $.fontsModul.fontsView.setTextObjectTable(objName, $.fontsModul.fontsController.fontOptions, resultText, false);
                $.fontsModul.fontsController.newTextObjectAfterAddTable();
                // Pridam do pole textObjects radek pro editaci z tabulky
                $.fontsModul.fontsController.textObjects[objName] = []; 
				
				$.fontsModul.fontsController.textObjects[objName].push({
                    objName: objName,
                    fontObjects: $.fontsModul.fontsController.fontOptions,
                    resultText: resultText
                });
            }
            else {
				jQuery.log.error($.core.getTextResourceByKey("ERROR_1", $.fontsModul.gloablOptions.textResourceList), "");                
            }
        },
        
        /**
         * Po vlozeni do tabulky se resetuje vytvoreni noveho textu.
         * Do nazvu objectu se da novy nahodny text a ostatni inputy se vyprazdni.		 *
         */
        newTextObjectAfterAddTable: function(){
            var objectName = $.fontsModul.gloablOptions.objectName;
            var fontTypeSelect = $.fontsModul.gloablOptions.fontTypeSelectBox;
            var customerText = $.fontsModul.gloablOptions.customerText;
            var resultText = $.fontsModul.gloablOptions.resultText;
            
            this._textObjectNum = (this._textObjectNum + 1);
            $.fontsModul.fontsView.setEmptyTextObject(objectName, fontTypeSelect, customerText, resultText, this._textObjectNum);            
        },
        
        _clearTextObjectData: function() {
        	var objectName = $.fontsModul.gloablOptions.objectName;
            var fontTypeSelect = $.fontsModul.gloablOptions.fontTypeSelectBox;
            var customerText = $.fontsModul.gloablOptions.customerText;
            var resultText = $.fontsModul.gloablOptions.resultText;
            
            this._textObjectNum = 1;
            $.fontsModul.fontsView.setEmptyTextObject(objectName, fontTypeSelect, customerText, resultText, this._textObjectNum);
        },
        
        /***
         * Metoda vraci obsah tabulky s uzivatelskyma objectama pro ulozeni na server
         * k obednavce.
         */
        resultTextObject: function(){
        
            var fontTypeSelect = $.fontsModul.gloablOptions.fontTypeSelectBox.find('option:selected').val();
            
            //Data of table
            var table = $.fontsModul.gloablOptions.textObjectTable;
            if (table.find('tr').length > 1) {
                //TODO dodelat vraceni obsahu tabulky ve formatu #TextObejctName,fontTypeCode,CustomerText;#TextObjectName,fontTypeCode,CustomerText
            }
        },
        
        /**
         * Metoda se zavola po kliknuti na ikonku delete.
         * Zavola se dialogove okno. Zda ma byt object smazan.
         * Pokud ano smaze textObject z tabulky.
         */
        removeTextObjectOfTableOnClick: function(el){
            var tr = $(el).moveToParent('TR');			
            if (confirm($.core.getTextResourceByKey("CONFIRM_REMOVE_OBJECT_1", $.fontsModul.gloablOptions.textResourceList))) {
                $.fontsModul.fontsView.removeRowOfObjectTable(tr);
            }
            else {
                return false;
            }
        },
        
        /***
         * Metoda se zavola po kliknuti na editovat radek v object table.
         * Metoda nastavi zonu Object Text z hodnot tabulky.
         *
         * $.motiveandfonts.fontsView.setObjectsTextEdit() ma parametry
         * @param {Object} elObjectText
         * @param {Object} objectText
         * @param {Object} elSelectFontType
         * @param {Object} selectFontType
         * @param {Object} elInputText
         * @param {Object} inputText
         * @param {Object} elResultText
         * @param {Object} resultText
         */
        editTextObjectOnClick: function(el){
            var rowObjectText = $.trim($(el).moveToParent('TR').find('td:first').text());
            var textObjects = $.fontsModul.fontsController.textObjects[rowObjectText][0];
            var objectName = $.fontsModul.gloablOptions.objectName;
            var fontTypeSelect = $.fontsModul.gloablOptions.fontTypeSelectBox;
            var customerText = $.fontsModul.gloablOptions.customerText;
            var resultText = $.fontsModul.gloablOptions.resultText;
            
            
            $.motiveandfonts.fontsView.changeRowTableAfterClickEdit($(el).moveToParent('TR'));
            $.motiveandfonts.fontsView.setObjectsTextEdit(objectName, textObjects.objName, fontTypeSelect, textObjects.fontObjects.code, customerText, textObjects.resultText, resultText, textObjects.resultText);
            $.motiveandfonts.fontsView.displayStaticFontImage(textObjects.fontObjects);
            // Change link na edit
            $($.fontsModul.gloablOptions.linkAddTextObjectToTable).unbind('click', $.fontsModul.fontsController.addTextObjectToTable).bind('click', $.fontsModul.fontsController.editTextObjectTable);
        },
        
		/***
		 * Metoda zmeni editovatelnou hodnotu novou
		 * 
		 */
        editTextObjectTable: function(){			
            var objName = $.fontsModul.gloablOptions.objectName.val();
            var resultText = $.fontsModul.gloablOptions.resultText.text();
            
            if ($.trim(resultText) != '' &&
            $.fontsModul.fontsController.isSetHead.length != 0) {
            
                $.fontsModul.fontsView.setTextObjectTable(objName, $.fontsModul.fontsController.fontOptions, resultText, true);
                //Clear
                $.fontsModul.fontsController.newTextObjectAfterAddTable();
                
                // Pridam do pole textObjects radek pro editaci z tabulky				
                $.fontsModul.fontsController.textObjects[objName] = [];
                $.fontsModul.fontsController.textObjects[objName].push({
                    objName: objName,
                    fontObjects: $.fontsModul.fontsController.fontOptions,
                    resultText: resultText
                });
                
            }
            else {
                jQuery.log.error($.core.getTextResourceByKey("ERROR_1", $.fontsModul.gloablOptions.textResourceList), "");
            }
        },
		
		/***
		 * Metoda vrati {Array} s textObject, fontType a customerText pro vlozeni ke zbozi. 
		 * Pokud uzivatel vytvoril tabulku tak ji projde a nebo se podiva do poli kde uzivatel psal udaje. 
		 * Jelikoz uzivatel nemusi vytvaret tabulku
		 * a po pridani ke zbozi by se nic nepridalo.
		 */
		getTextObjectList: function(){
		
			var fontList = [];
			var table = $.fontsModul.gloablOptions.textObjectTable;
			$.each($(table).find('tr'), function(index, value){
				//skip tr > th
				if (index > 0) {
					var textObjectName = $(value).children().eq(0).text();
					var fontTypeCode = $(value).children().eq(1).find('input[type="hidden"]:first-child').val();
					var customerText =  $(value).children().eq(2).text();
					
					if ($.stringIsNullOrEmpty(textObjectName) &&
					$.stringIsNullOrEmpty(fontTypeCode) &&
					$.stringIsNullOrEmpty(customerText)) {
						
						var fontTypeObject = new Object;
						fontTypeObject.textObjectName = textObjectName;
						fontTypeObject.fontTypeCode = fontTypeCode;
						fontTypeObject.customerText = customerText;
						
						fontList.push(fontTypeObject);
					}
				}
			});		
					
			
			var objName = $.fontsModul.gloablOptions.objectName.val();
			var resultText = $.fontsModul.gloablOptions.resultText.text();
			
			if ($.trim(resultText) != '' &&
			$.fontsModul.fontsController.isSetHead.length != 0) {
				var fontTypeObject = new Object;
				fontTypeObject.textObjectName = objName;
				fontTypeObject.fontTypeCode = $.fontsModul.fontsController.fontOptions.code;
				fontTypeObject.customerText = resultText;			
				
				fontList.push(fontTypeObject);								
			}
			
			//return fontList.join(';');
			return $.toJSON(fontList);
		},
		
		/***
		 * Zrusit veskery vyber a udalosti.
		 */					
		destory: function() {
			//Remove table if is create
			$.fontsModul.gloablOptions.textObjectTable.remove();
			//Clear array
			$.fontsModul.fontsController.textObjects = [];
			this._clearTextObjectData();
		}        
    }),
    /*======= FONTS VIEW ======*/
    fontsView: ({
    	
        setFontTypesSelectBox: function(el, fontTypeList, controllerName){
            el.children().detach();
            el.append('<option value="" selected="selected">-- Vybrat typ fontu --</option>');
            $.each(fontTypeList, function(index, values){
                el.append('<option value="' + values.code + '">' + values.name + '</option>');
            });
            el.live('change', controllerName);
        },
        
        setResultText: function(fontOption, customerText){
            var el = $.fontsModul.gloablOptions.resultText;
            
            if (customerText == null) {
                el.css({
                    'font-family': fontOption.code,
                    'font-size': '1.5em'
                });
            }
            else {
                el.html(customerText).css({
                    'font-family': fontOption.code,
                    'font-size': '1.5em'
                });
            }
            
        },
        
        setTextObjectTable: function(objName, fontOptions, resultText, isEdited){
            var el = $.fontsModul.gloablOptions.textObjectTable;
            var trTmpl = ("<tr><td>{0}</td><td><input type=\"hidden\" value=\"{3}\" />{1}</td><td>{2}</td><td><img src=\"/Content/moduls/MotiviesAndFonts/images/edit.gif\" title=\"{4}\" onclick=\"javascript: $.fontsModul.fontsController.editTextObjectOnClick(this);\" />&nbsp;<img src=\"/Content/moduls/MotiviesAndFonts/images/del.gif\" title=\"{5}\" onclick=\"javascript: $.fontsModul.fontsController.removeTextObjectOfTableOnClick(this);\" /></td>");
            
            if (isEdited) {
                $(el).find('tr > td:contains(' + objName + ')').moveToParent('TR').remove()
            }
            
            el.fadeIn('slow', function(){
                $(this).append($.format(trTmpl, 
				objName, 
				fontOptions.name, 
				resultText, 
				fontOptions.code,
				$.core.getTextResourceByKey("TABLE_FONTTYPE_IMAGE_TITLE_EDIT", $.fontsModul.gloablOptions.textResourceList),
				$.core.getTextResourceByKey("TABLE_FONTTYPE_IMAGE_TITLE_DELETE", $.fontsModul.gloablOptions.textResourceList)));
            });
            
        },
        
        /****
 		* Smaze radek z tabulky text-object-table
 		* @param {Object} row
 		*/
        removeRowOfObjectTable: function(row){
            $(row).remove();
        },
        
        setFontFaceToHead: function(fontOption){            
             $('head').append(
             "<style type=\"text/css\" media=\"screen, print\">" +
             "@font-face {font-family: '" + fontOption.code + "'; "+ 
             "src: url('" + fontOption.srcEOT + "'); "+
             "src: local('˘'),"+
             "url('" + fontOption.srcWOFF + "') format('woff'),"+
             "url('" + fontOption.srcTTF + "') format('truetype'),"+
             "url('" + fontOption.srcSVG + "#" + fontOption.code + "') format('svg');"+
             "font-weight: normal;	font-style: normal;}</style>");
        },
        
        /****
		 * Zobrazi vysledny obrazek jak by mohl typ fontu vypadat.
		 * Jedna se zejmena kdyz uzivatel nemam aktualizovany prohlizec
		 * a font se mu neukazuje spravne.
		 * @param {Object} fontOptions
		 */
        displayStaticFontImage: function(fontOptions){
            ($.fontsModul.gloablOptions.staticFontImage).empty().append($.format('<img src="{2}static_preview/{0}.gif" alt="{1}">', fontOptions.code, fontOptions.name, $.fontsModul.gloablOptions.fontFolder)).css({
                'padding': '0',
                'margin': '0'
            });
        },
        
        /**
		 * Vyprazdni vsechny inputy v object textu.
		 * @param {Object} elObjText
		 * @param {Object} elSelectFontType
		 * @param {Object} elInputText
		 * @param {Object} elResultText
		 */
        setEmptyTextObject: function(elObjText, elSelectFontType, elInputText, elResultText, textObjectNum){        	 
            //Math.floor(Math.random() * 100) + parseInt(100)
            $(elObjText).val('#TEXT_' + textObjectNum);
            $(elSelectFontType).find("option:first").attr('selected', 'selected');
            $(elInputText).val('');
            $(elResultText).empty();
            ($.fontsModul.gloablOptions.staticFontImage).empty();
        },
        
        /****
		 * Nastavi objectsText po kliknuti na editaci v tabulce
		 * @param {Object} elObjectText
		 * @param {Object} objectText
		 * @param {Object} elSelectFontType
		 * @param {Object} selectFontType
		 * @param {Object} elInputText
		 * @param {Object} inputText
		 * @param {Object} elResultText
		 * @param {Object} resultText
		 */
        setObjectsTextEdit: function(elObjectText, objectText, elSelectFontType, selectFontType, elInputText, inputText, elResultText, resultText){
            $(elObjectText).val(objectText);
            $(elSelectFontType).find("option[value=" + selectFontType + "]").attr('selected', 'selected');
            $(elInputText).val(inputText);
            $(elResultText).text(resultText);
        },
        
        /**
		 * Zmeni barvu pozadi radku tabulky po kliknuti na editaci
		 * @param {Object} el
		 */
        changeRowTableAfterClickEdit: function(el){
            $(el).css({
                'background-color': '#ececec'
            })
        }
    }),
    
    runFontsModul: function(settings){
        $.fontsModul.fontsController._init(settings);
    }
});

/**********************************************************/
/********* SPECIAL INSTRUCTIONS MODUL *********************/
/**********************************************************/
jQuery.specialInstructionsModul = ({

    gloablOptions: {},
    
    specialModel: ({}),
    
    specialController: ({
    
        _init: function(settings){
            $.extend($.specialInstructionsModul.gloablOptions, settings);
            
        },
        
        getSpecialIntructions: function(){
        	return $("div#motives-fonts-description textarea#specialInstructions-note").val();
        }
        
    }),
    
    specialView: ({}),
    
    runSpecialInstructionsModul: function(settings){
        $.fontsModul.specialController._init(settings);
    }
    
});

/***======== Core utils =========***/
/**
 * Spolecna utilitni trida pro cely modul
 **/
jQuery.core = ({
	/***
	 * Metoda vraci text z resourceListu podle klice.
	 * 
	 * @param {String} key - klic podle ktereho se bude vyhledavat
	 * @param {Array} resourceList - list se zdrojem textu
	 */
	getTextResourceByKey: function(key, resourceList) {
		var value = '';
		if ($.stringIsNullOrEmpty(key)) {
			$.each(resourceList, function(index, values){
				if($.trim(values.key.toUpperCase()) == $.trim(key.toUpperCase())) {					
					return value = values.value;
				}
			});
		} else {
			$.log.error("Nelze vyhledavat v resourceList jeliko� kl�� je pr�zdn�!", "");
		}
		
		return value;
	},
	/**
	 * Metoda se zavola kdyz uzivatel kline na "Pridat ke zbozi".
	 * Vraci object {motivesAndFonts} ktery v sobe ma attributy {motives}
	 * ktery ma string object CatCode_MotiveCode oddelene strednikem. 
	 * Nasledne druhy attribute {fonts} ktery v sobe ma string object fonts=>TextObjectCode_FontType_UserText oddelenej strednikem.
	 * Posledni attribute ktery v sobe ma je {note} coz je poznamka k motivu a fontu. 
	 * 
	 * motiveAndFontType = {
	 * 		motives: "",
	 * 		fontTypes: ""	  		
	 * }  
	 */
	 getMotiveAndFonts: function() {	 	
		return motiveAndFontTypes =  {
			motives: $.motiveModul.motiveController.motiveImageCheckedList.join(';'),
			fontTypes: $.fontsModul.fontsController.getTextObjectList(),
			specialInstructions: $("div#motives-fonts-description textarea#specialInstructions-note").val()		
		}
	}
});
/***=============================***/

/** Run moduls **/
jQuery.motiveandfonts = ({
	
    version: '0.0.2',
    
    runApps: function(options){
		
        if (options.settingsMotiveModul.activeModule) 
            $.motiveandfonts.runMotiveModul(options.settingsMotiveModul);
        
        if (options.settingsFontsModul.activeModule) 
            $.motiveandfonts.runFontsModul(options.settingsFontsModul);
    }
    
});

$.extend(jQuery.motiveandfonts, $.fontsModul, $.motiveModul, $.specialInstructionsModul, $.core);


