﻿//namespace
if (typeof GP == "undefined") { var GP = {}; }
if (typeof GP.util == "undefined") { GP.util = {}; }

/** динамическое создание css селекторов*/
GP.util.Style=function(rules) {
	var $C=YAHOO.util.Connect, $E=YAHOO.util.Event, $D=YAHOO.util.Dom, $=YAHOO.util.Dom.get;
	var styleElement=null;
	var styleSheet=null;

	/** 
	 * заполняет правилами элемент style
	 * @return Node
	 */
	var fillStyleElement = function(rules) {
		for (var i in rules)
			addStyleSelector(i,rules[i]);
	}

	/**
	 *  создает элемент style и добавляет его в заголовок
	 *  @return Node
	 */
	var createAndAppendStyleElement = function(callback) {
		styleElement = $('style_nojs');
		if (styleElement) {
			var id = $D.generateId(styleElement,"style");
		} else {
			styleElement=document.createElement('style');
			styleElement.setAttribute("type", "text/css");
			var id = $D.generateId(styleElement,"style");
			document.getElementsByTagName('head')[0].appendChild(styleElement);
		}
		
		
		if(document.styleSheets && document.styleSheets.length && document.styleSheets[0].addRule){ // ie
			for (var i in document.styleSheets)
				if (document.styleSheets[i].id == id)
					styleSheet = document.styleSheets[i];
		}
		if(callback) callback(style);
		fixIEBug();
	};
	
	/**
	 * добавляет селектор в элемент style
	 * @param Node style - ссылка на элемент style
	 * @param string selector - css selector
	 * @param string rules - css правила
	 * @return (Node) selector - дескриптор созданного правила, по которому его можно удалить
	 */
	var addStyleSelector = function(selector,rules) {
		if (styleSheet && styleSheet.addRule){ //ie
			selector=selector.split(',');
			var s=selector.length;
			while(s--) { 
				styleSheet.addRule(selector[s],rules);
			}
		} else {// w3c
			var cssText = document.createTextNode(selector+' {'+rules+'}');
			styleElement.appendChild(cssText);
		}
	};

	/**
	 * удаляет елемент style из документа
	 * @param Node style - ссылка на елемент style
	 */
	var removeStyleElement = function(style) {
		if (styleSheet && styleSheet.addRule){ //ie
			styleSheet.cssText = "";
		}
		document.getElementsByTagName('head')[0].removeChild(styleElement);
		fixIEBug();
	};
	
	/**
	 * @todo сделать через custom events
	 */
	var fixIEBug = function() {
		var body=document.getElementsByTagName('body')[0];
		body.style.position='relative';
		body.style.position='static';
	};
	createAndAppendStyleElement(null);
	if (rules) fillStyleElement(rules);
	return {
		create:function(rules){if (styleElement) removeStyleElement(); createAndAppendStyleElement(null); fillStyleElement(rules);},
		clear:function(){if (styleElement) removeStyleElement(); createAndAppendStyleElement(null);},
		destroy:function(){removeStyleElement();}
	}
};