

var FontCategory = Class.create({
	CLASSDEF: {
		name: 'FontCategory'
	},
	
	initialize: function(id, name) {
		this.id = id;
		this.name = name;
		this.childFonts = [new MapList(this),new MapList(this),new MapList(this),new MapList(this)]; //0 = non emb, 1 = emb
		this.childCategories = new MapList(this);
		this.cachedCodeString = [null,null, null, null];
		this.cat=null;
		this.subcat=null;
	},
	
	addCategory: function(category) {
		this.childCategories.add(category);
	},
	
	addFont: function(font) {
		if(font.normalFont) {
			//log("Adding Normal Font " + font.name + " to " + this.name);
			this.childFonts[0].add(font);
      //if(font.utf8) {
      //  this.childFonts[2].add(font);
      //}
		}
		if(font.embFont) {
			//log("Adding EMB Font " + font.name + " to " + this.name);
			this.childFonts[1].add(font);
      //if(font.utf8) {
      //  this.childFonts[3].add(font);
      //}
		}
		if(this.parentObject != null) {
			this.parentObject.addFont(font);
		}
	},
	
	filterUtf8Fonts: function(baseIndex, usedPages) {
	  this.childFonts[baseIndex+2] = new MapList(this);
	  var utfList = this.childFonts[baseIndex+2];
	  var fontList = this.childFonts[baseIndex];
	  for(var i=0; i < fontList.list.length; i++) {
	    var fontDef =  fontList.list[i];
	    if(fontDef.supportsPages(usedPages)) {
	      utfList.add(fontDef);
	    }
	  }
	  if(this.childCategories != null) {
	    if(this.cachedCategories!=null) {
	      this.cachedCategories[baseIndex+2] = null;
	    }
      for(var i=0; i < this.childCategories.list.length; i++) {
        this.childCategories.list[i].filterUtf8Fonts(baseIndex, usedPages);
      }
    }
	},
	
	firstCat: function(fontIndex) {
		for(var i=0; i < this.childCategories.list.size(); i++) {
			var cat = this.childCategories.list[i];
			if(cat.hasFonts(fontIndex)) {
				return cat;
			}
		}
	},
	
	hasFonts: function(fontIndex) {
		return (this.childFonts[fontIndex].list.size() > 0);
	},
	
	filteredCategories: function(fontIndex) {
		if(this.cachedCategories == null) {
			this.cachedCategories = {};
		}
		if(this.cachedCategories[fontIndex] != null) {
			return this.cachedCategories[fontIndex];
		}
		var result = [];
		for(var i=0; i < this.childCategories.list.size(); i++) {
			var cat = this.childCategories.list[i];
			if(cat.hasFonts(fontIndex)) {
				result.push(cat);
			}
		}
		this.cachedCategories[fontIndex] = result;
		return result;
	}
});


var FontSelector = Class.create({
	CLASSDEF: {
		name: 'FontSelector',
		parent: FontCategory
	},
	
	initialize: function() {
		FontSelector.parentClass.constructor().call(this, 0, "root");
		this.allCategories = {};
		this.allFonts = {};
		this.fontSelectorDiv = [null,null,null,null];
		this.selectedFont = [null,null,null,null];
		this.selectedCat = [null,null,null,null];
		this.selectedSubCat = [null,null,null,null];
    this.utf8Pages = null;
    this.allCategories[0] = this;
	},
	
	addCategory: function(category, parentId) {
		if(parentId == null) {
      log("Adding " + category.name + " to root");
      this.childCategories.add(category);
		} else {
			var parent = this.allCategories[parentId];
			log("Adding " + category.name + " to " + parent.name);
			parent.addCategory(category);
		}
		this.allCategories[category.id] = category;
	},
	
	addFont: function(font) {
		this.allFonts[font.name] = font;
		FontSelector.parentClass.method("addFont").call(this, font);
		
	},
	
	
	selectFont: function(currentFont, defaultFont, embMode, callback) {
		log("FontSelector.selectFont");
		this.callback = callback;
		this.fontIndex = embMode ? 1 : 0;
		
    if(this.utf8Pages != null) {
      var codeString = "";
      for(var k in this.utf8Pages) {
        codeString += k + ";";
      }
      if(codeString != this.cachedCodeString[this.fontIndex + 2]) {
        this.filterUtf8Fonts(this.fontIndex, this.utf8Pages);
        this.cachedCodeString[this.fontIndex + 2] = codeString;
        if(this.fontSelectorDiv[this.fontIndex + 2] != null) {
          this.fontSelectorDiv[this.fontIndex + 2].remove();
          this.fontSelectorDiv[this.fontIndex + 2] = null;
        }
      }
      this.fontIndex += 2;
    }
		if(currentFont == null) {
			currentFont = defaultFont;
		}
		
		var font = this.allFonts[currentFont];
		if(font==null) {
			font = this.allFonts[defaultFont];
		}
		if(font==null) {
			alert("Unable to get font data");
			return;
		}
		
		if((this.fontSelectorDiv[this.fontIndex]==null)) {
			this.buildFontSelector(font);
		} else {
			log("Already Open");
      var selFont = this.childFonts[this.fontIndex].byId[font.id];
      if(selFont == null) {
        log("Selected Font (" + font.name + ") is not available in fontIndex " + this.fontIndex);
        selFont = this.childFonts[this.fontIndex].list[0];
        if(selFont == null) {
          log("no available fonts");
        } else {
          font = selFont;
        }
      }
			this.toggleFontCat(0); //font.category.id);
			//if(font.subCategory!=null) {
			//	this.selectFontSubCat(font.subCategory.id);
			//}
			this.toggleFont(font.id);
			popup("pwSelectFont_" + this.fontIndex);
		}
		//if(this.fontSelected!=null) {
			var el = $("pwFontCell_" + font.id + "_" + this.fontIndex);
			if(el != null) {
			  try {
          var offsetElement = Position.offsetParent(el);
          var offset = Position.positionedOffset(el);
          
          var scrollElement = $('pwFontListingUl_' + this.fontIndex);
          var scrollOffset = Position.positionedOffset(scrollElement);
          
          var sOffset = offset[1] - scrollOffset[1];
          if(sOffset > 100) {
            scrollElement.scrollTop = sOffset - 100;
          }
        } catch(e) {} //fail silently...
			}
		//}
	},
	
	buildFontSelector: function(font) {
		
		log("FontSelector.buildFontSelector, this.fontIndex=" + this.fontIndex);
		//<div id="add_text" class="popup font_sel clearfix">
		
		var html = '<div class="popup_box"><div class="popup_int"><h3 class="empty"><b>' + pwFontSelectorHeading + '</b></h3>';
		html += '<div class="popup_content">';
			html += '<div class="library_browser font">';
				html += '<div class="library_header">';
					html += '<div class="hierarchy">';
						html += "<div>";
							html += "<h4>Font Categories</h4>";
						html += "</div>";
					html += "</div>";
					html += '<div class="listing">';
						html += "<div>";
							html += "<h4>Font Listing</h4>";
						html += "</div>";
					html += "</div>";
				html += '</div>';
				html += '<div class="interior">';
					html += '<div class="hierarchy"><div class="library_categories">';
					
					html += '<ul class="fonts" id="pwFontSelCatBox_' + this.fontIndex + '">';
						  html += '<li><span class="rootfont selected" id="pwFontCatLi_0_' + this.fontIndex + '"><a class="null" href="#">&nbsp;</a><a href="#" onclick="pwFontManager.toggleRootCat(); return false;" class="link">All</a></span><ul>'	
						
						var cats = this.filteredCategories(this.fontIndex);
						
						for(var i=0;i < cats.length;i++) {
							var cHtml = this.buildFontSelectorCat(cats[i], font);
							if(cHtml != null) {
								html += cHtml;
							}
						}
						html += '</ul></li></ul>';
					html += '</div></div>';
					html += '<div class="listing">';
						html += '<ul class="font_listing" id="pwFontListingUl_' + this.fontIndex + '">';
						
						//html += this.buildFontList(this.selectedCat[this.fontIndex],this.selectedSubCat[this.fontIndex], font);
						html += this.buildFontList(this,null, font); //load all fonts
					
						html += '</ul>';
					html +='</div>';
				html +='</div>';
			html +='</div>';
		html += '</div>';
		html += '<div class="foot"><b><input type="button" value="' + pwFontSelectorCancelCaption + '" class="button cancel" onclick="closePopup(\'pwSelectFont_' + this.fontIndex + '\'); return false;"/> <input type="button" value="' + pwFontSelectorOKCaption + '" class="button" onclick="pwFontManager.selectCurrentFont(); return false;"/></b></div></div></div>';
		
		//</div>

		this.fontSelectorDiv[this.fontIndex] = document.createElement("DIV");
		this.fontSelectorDiv[this.fontIndex].className = "popup font_selector";
		this.fontSelectorDiv[this.fontIndex].id = "pwSelectFont_" + this.fontIndex;
		this.fontSelectorDiv[this.fontIndex].setAttribute("stopdeselect","true");
		this.fontSelectorDiv[this.fontIndex].innerHTML = html;
		document.body.appendChild(this.fontSelectorDiv[this.fontIndex]);
		
		popup("pwSelectFont_" + this.fontIndex);
	},

	buildFontSelectorCat: function(cat, font) {
		this.selectedFont[this.fontIndex] = font;
		var clz = "";
		var style = ' style="display:none;"';
		var cats = cat.filteredCategories(this.fontIndex);
		/*if(cat == font.category) {
			//clz = ' class="selected"';
			if(cats.length > 0) {
				style = "";
			}
			this.selectedCat[this.fontIndex] = font.category;
		}*/
		
		var html = '<li id="pwFontCatLi_' + cat.id + '_' + this.fontIndex + '"><span' + clz + '>';
		if (cats.length>0/* && cat != font.category*/) html += '<a href="#" class="open" id="int_icon_'+cat.id+'" onclick="pwFontManager.toggleFontCat(' + cat.id + '); return false;">&nbsp;</a>';
		//else if (cats.length>0 && cat == font.category) html += '<a href="#" class="close" id="int_icon_'+cat.id+'" onclick="pwFontManager.toggleFontCat(' + cat.id + '); return false;">&nbsp;</a>';
		else html += '<a href="#" class="null" id="int_icon_'+cat.id+'" onclick="pwFontManager.toggleFontCat(' + cat.id + '); return false;">&nbsp;</a>';
		html +='<a href="#" onclick="pwFontManager.toggleFontCat(' + cat.id + '); return false;" class="link">' + cat.name + '</a></span>';
		html += '<ul id="pwFontCatUl_' + cat.id + '_' + this.fontIndex + '"' + style + '>';
		
		for(var i=0; i < cats.length; i++) {
			var subCat = cats[i];
			clz = "";
			/*if(subCat == font.subCategory) {
				clz = ' class="selected"';
				this.selectedSubCat[this.fontIndex] = font.subCategory;
			}*/
			var sHtml = '<li id="pwFontCatLi_' + subCat.id + '_' + this.fontIndex + '"><span' + clz + '><a href="#" class="null">&nbsp;</a><a href="#" class="link" onclick="pwFontManager.selectFontSubCat(' + subCat.id + '); return false;" class="cat_label">' + subCat.name + '</a></span></li>';
			html += sHtml;
		}
		html += '</ul></li>';
		return html;
		
	},
	
	buildFontList: function(category, subCategory, currentFont) {
		if(category==null && subCategory==null) {
      return "";
    }
		var fontList = subCategory == null ? category.childFonts[this.fontIndex].list : subCategory.childFonts[this.fontIndex].list;
		var html = "";
		var prefix = this.fontIndex % 2 == 0 ? "" : "emb_";
		for(var i=0; i < fontList.size();i++) {
			var font = fontList[i];
			var clz = "";
			if(font == currentFont) {
				clz = ' class="alt"';
				this.selectedFont[this.fontIndex] = currentFont;
			}
			var fHtml = '<li id="pwFontCell_' + font.id + '_' + this.fontIndex + '"' + clz + ' onclick="pwFontManager.toggleFont(\'' + font.id + '\');" ondblclick="pwFontManager.toggleFont(\'' + font.id + '\'); pwFontManager.selectCurrentFont();"; onmousemove="pwSelFontMm(this);" onmouseout="pwSelFontMo(this);"><img src="/ppr/text_font/sample/' + font.id + '/' + prefix + 'sample.gif" border="0"><span>' + font.name + '</span></li>';
			html += fHtml;
		}
		return html;
	},
	
	selectCurrentFont: function() {
		if(this.callback!=null) {
			this.callback(this.selectedFont[this.fontIndex].name, this.selectedFont[this.fontIndex]);
		}
		closePopup("pwSelectFont_" + this.fontIndex);
	},
	
	toggleRootCat: function() {
	  this.toggleFontCat(0);
	},
	
	toggleFontCat: function(catId) {
		
		curr_li=$$("#pwFontCatUl_"+this.cat+"_0 li span");
		for(x=0; x<curr_li.length; x++) curr_li[x].className=null;
		
		var selCat = this.selectedCat[this.fontIndex];
		//if((selCat == null)||(selCat.id != catId)) {
			if(selCat != null) {
				//deselect existing...
				var el = document.getElementById("pwFontCatLi_" + selCat.id + "_" + this.fontIndex);
				if(selCat.id != 0) {
				  el=el.getElementsByTagName('span')[0];
				  el.className = "";
				  
				  el = document.getElementById("pwFontCatUl_" + selCat.id + "_" + this.fontIndex);
				  el.style.display = "none";
				
          //icon class change
          var fl = document.getElementById("int_icon_"+selCat.id);
          var int_class = (fl.className=="null") ? "null" : "open";
          fl.className = int_class
        } else {
          el.className = "rootfont";
        }
			}
			selCat = this.allCategories[catId];
			this.selectedCat[this.fontIndex] = selCat;
			this.selectFontSubCat(null);
			var el = document.getElementById("pwFontCatLi_" + selCat.id + "_" + this.fontIndex);
			if(catId == 0) {
			  el.className = "rootfont selected";
			} else {
        if(el != null) {
          el=el.getElementsByTagName('span')[0];
        //var el=$$("pwFontCatLi_" + selCat.id + "_" + this.fontIndex+" span")[0];
          el.className = "selected";
          
          var li = el.getElementsByTagName('li');
          for(y=0; y<li.length; y++)
            li[y].className=null;
        }
      }
      
			//icon class change
			var fl = document.getElementById("int_icon_"+selCat.id);
      if(fl != null) {
			var int_class=(fl.className=="null") ? "null" : "close";
        fl.className = int_class
			}
			if(selCat.filteredCategories(this.fontIndex).length != 0) {
				el = document.getElementById("pwFontCatUl_" + selCat.id + "_" + this.fontIndex);
        if(el != null) {
          el.style.display = "";
        }
			}
		//}
		el = document.getElementById("pwFontListingUl_" + this.fontIndex);
    if(el != null) {
      el.innerHTML = this.buildFontList(selCat, null, this.selectedFont[this.fontIndex]);
    }
    this.cat=catId;
	},
	
	selectFontSubCat: function(subCatId) {
		var selCat = this.selectedSubCat[this.fontIndex];
		if(selCat != null) {
			if(selCat.id == subCatId) {
				return;
			}
			//deselect existing...
			var el = document.getElementById("pwFontCatLi_" + selCat.id + "_" + this.fontIndex);
			el=el.getElementsByTagName('span')[0];
			el.className = "";
		}
		if(subCatId!=null) {
			selCat = this.allCategories[subCatId];
			this.selectedSubCat[this.fontIndex] = selCat;
			var el = document.getElementById("pwFontCatLi_" + selCat.id + "_" + this.fontIndex);
      if(el != null) {
			el=el.getElementsByTagName('span')[0];
        el.className = "selected";
			el.parentNode.parentNode.parentNode.getElementsByTagName('span')[0].className=null;
        el = document.getElementById("pwFontListingUl_" + this.fontIndex);
        el.innerHTML = this.buildFontList(this.selectedCat[this.fontIndex], selCat, this.selectedFont[this.fontIndex]);
      }
		} else {
			this.selectedSubCat[this.fontIndex] = null;
		}
	},
	
	toggleFont: function(fontId) {
		var selFont = this.selectedFont[this.fontIndex];
		if(selFont!=null) {
			var el = $("pwFontCell_" + selFont.id + "_" + this.fontIndex);
			if(el != null) {
				el.className = "";
			}
		}
		selFont = this.childFonts[this.fontIndex].byId[fontId];
    if(selFont != null) {
      this.selectedFont[this.fontIndex] = selFont;
      var el = $("pwFontCell_" + selFont.id + "_" + this.fontIndex);
      if(el != null) {
        el.className = "alt";
      }
    }
	}
});

var Font = Class.create({
	CLASSDEF: {
		name: 'Font'
	},
	
	initialize: function(options, category, subCategory) {
		this.id = options.id;
		this.name = options.name;
		this.bold = options.b;
		this.italics = options.i;
		this.boldItalics = options.bi;
		this.utf8 = options.u;
		this.category = category;
		this.subCategory = subCategory;
		this.normalFont = options.nf;
		this.embFont = options.ef;
    this.minSize = options.ms;
    this.languageCodes = options.lc.split(' ');
		if(subCategory != null) {
			subCategory.addFont(this);
		} else if(category != null) {
			category.addFont(this);
		}
	},
	
	getSampleURL: function(isEmb) {
		var prefix = isEmb ? "emb_" : "";
		return "/ppr/text_font/sample/" + this.id + "/" + prefix + "mp2.png";
	}, 
	
	supportsPages: function(pages) {
	  for(var i=0; i < this.languageCodes.length; i++) {
	    if(pages[this.languageCodes[i]]) return true;  
	  }
	  return false;
	}
});

var pwFontManager = new FontSelector();


function pwSelFontMo(el) {
	if(el.className != "alt") {
		el.className = "";
	}
}

function pwSelFontMm(el) {
	if(el.className != "alt") {
		el.className = "font_rollover";
	}
}
