var cssDesignerConf = null;
var initDone = false;
var dirty = false;
var doLink = true;
var iframeStyleSheets=null;
var webSitePreviewOverlay=null;
var webSitePreview=null;

var designerStringRes = {
	0:{	controlBtnGroup:'Actions',
		saveBtn:'Sauver',
		quitBtn:'Quitter',
		resetBtn:'Init.',
		crop:'Sélectionner le cadrage',
		errorDlgTitle:'Erreur',
		successDlgTitle:'Sauvegarde',
		cancelBtn:'Annuler',
		noDirtyProperty:'Vous n\'avez pas fait de modifications depuis votre dernière sauvegarde. Une sauvegarde n\'est pas nécessaire.',
		confirmCancel:'Vous avez fait des modifications qui n\'ont pas été sauvegardées. Êtes-vous certain de vouloir quitter sans sauvegarder ces modifications ?',
		confirmReset:'Réinitialiser la présentation SmartSkin à ses valeurs par défaut et annuler les modifications effectuées ?'},
	1:{	controlBtnGroup:'Actions',
		saveBtn:'Save',
		quitBtn:'Quit',
		resetBtn:'Reset',
		crop:'Crop Configuration',
		errorDlgTitle:'Error',
		successDlgTitle:'Save',
		cancelBtn:'Cancel',
		noDirtyProperty:'You haven\'t made any changes since your last save.',
		confirmCancel:'Your changes have not been saved. Do you really want to quit without saving these changes?',
		confirmReset:'Reset the SmartSkin design with the initial values and cancel your changes?'},
	2:{	controlBtnGroup:'Acciones',
		saveBtn:'Guardar',
		quitBtn:'Salir',
		resetBtn:'Iniciar',
		crop:'Seleccionar el marco',
		errorDlgTitle:'Error',
		successDlgTitle:'Guardar',
		cancelBtn:'Cancelar',
		noDirtyProperty:'No ha hecho cambios desde la última actualización. No es necesario guardar los cambios.',
		confirmCancel:'Ha realizado cambios que aún no ha guardado. ¿Desea realmente salir sin guardar estos cambios?',
		confirmReset:'Reiniciar la presentación  SmartSkin por los valores predeterminados y cancelar los cambios realizados'},
	4:{	controlBtnGroup:'Azioni',
		saveBtn:'Salva',
		quitBtn:'Esci',
		resetBtn:'Iniz.',
		crop:'Selezionnare l\'inquadratura',
		errorDlgTitle:'Errore',
		successDlgTitle:'Salvataggio',
		cancelBtn:'Annulla',
		noDirtyProperty:'Non hai fatto delle modifiche dopo il tuo ultimo salvataggio. Un salvataggio non è necessario.',
		confirmCancel:'Hai fatto delle modifiche che non sono state salvate. Sei sicuro di volere uscire senza salvare queste modifiche ?',
		confirmReset:'Reinizializzare la presentazione SmartSkin con questi valori predefiniti e annulare le modifiche effettuate ?'}
}

designerStringRes[3]=designerStringRes[5]=designerStringRes[1];

function getDefaultImgModel() {
	return [
{url:'/Images/cssdesigner/themes/digital-carre-violet.jpg', thumbnailUrl:'/Images/cssdesigner/themes/digital-carre-violet_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/digital-carre-vert.jpg', thumbnailUrl:'/Images/cssdesigner/themes/digital-carre-vert_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/digital-tache.jpg', thumbnailUrl:'/Images/cssdesigner/themes/digital-tache_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/digital-volute-rose.jpg', thumbnailUrl:'/Images/cssdesigner/themes/digital-volute-rose_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/digital-filaire.jpg', thumbnailUrl:'/Images/cssdesigner/themes/digital-filaire_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/digital-abstract.jpg', thumbnailUrl:'/Images/cssdesigner/themes/digital-abstract_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/ambiance-liquide.jpg', thumbnailUrl:'/Images/cssdesigner/themes/ambiance-liquide_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/ambiance-luxe.jpg', thumbnailUrl:'/Images/cssdesigner/themes/ambiance-luxe_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/taxi.jpg', thumbnailUrl:'/Images/cssdesigner/themes/taxi_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/service-coiffure.jpg', thumbnailUrl:'/Images/cssdesigner/themes/service-coiffure_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/sante-bien-etre.jpg', thumbnailUrl:'/Images/cssdesigner/themes/sante-bien-etre_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/ambiance-zen.jpg', thumbnailUrl:'/Images/cssdesigner/themes/ambiance-zen_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/sport-zen.jpg', thumbnailUrl:'/Images/cssdesigner/themes/sport-zen_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/cadeaux.jpg', thumbnailUrl:'/Images/cssdesigner/themes/cadeaux_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/mode-vetement.jpg', thumbnailUrl:'/Images/cssdesigner/themes/mode-vetement_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/ceintre.jpg', thumbnailUrl:'/Images/cssdesigner/themes/ceintre_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/chaussure.jpg', thumbnailUrl:'/Images/cssdesigner/themes/chaussure_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/medecine.jpg', thumbnailUrl:'/Images/cssdesigner/themes/medecine_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/medical-pomme.jpg', thumbnailUrl:'/Images/cssdesigner/themes/medical-pomme_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/pomme.jpg', thumbnailUrl:'/Images/cssdesigner/themes/pomme_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/croix-medical.jpg', thumbnailUrl:'/Images/cssdesigner/themes/croix-medical_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/interieur-deco.jpg', thumbnailUrl:'/Images/cssdesigner/themes/interieur-deco_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/lampe.jpg', thumbnailUrl:'/Images/cssdesigner/themes/lampe_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/artisan-batiment.jpg', thumbnailUrl:'/Images/cssdesigner/themes/artisan-batiment_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/artisan-outil.jpg', thumbnailUrl:'/Images/cssdesigner/themes/artisan-outil_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/corporate.jpg', thumbnailUrl:'/Images/cssdesigner/themes/corporate_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/aide.jpg', thumbnailUrl:'/Images/cssdesigner/themes/aide_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/fleur-rose.jpg', thumbnailUrl:'/Images/cssdesigner/themes/fleur-rose_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/petale-rose.jpg', thumbnailUrl:'/Images/cssdesigner/themes/petale-rose_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/rose.jpg', thumbnailUrl:'/Images/cssdesigner/themes/rose_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/restauration-alimentaire.jpg', thumbnailUrl:'/Images/cssdesigner/themes/restauration-alimentaire_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/alimentaire-fruits-legumes.jpg', thumbnailUrl:'/Images/cssdesigner/themes/alimentaire-fruits-legumes_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/alimentaire-fruit.jpg', thumbnailUrl:'/Images/cssdesigner/themes/alimentaire-fruit_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/alimentaire-legume.jpg', thumbnailUrl:'/Images/cssdesigner/themes/alimentaire-legume_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/alimentaire-pain.jpg', thumbnailUrl:'/Images/cssdesigner/themes/alimentaire-pain_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/alimentaire-pattes.jpg', thumbnailUrl:'/Images/cssdesigner/themes/alimentaire-pattes_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/alimentaire-pizza.jpg', thumbnailUrl:'/Images/cssdesigner/themes/alimentaire-pizza_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/animaux.jpg', thumbnailUrl:'/Images/cssdesigner/themes/animaux_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/art-graphique.jpg', thumbnailUrl:'/Images/cssdesigner/themes/art-graphique_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/engrenage.jpg', thumbnailUrl:'/Images/cssdesigner/themes/engrenage_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/film.jpg', thumbnailUrl:'/Images/cssdesigner/themes/film_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/automobile.jpg', thumbnailUrl:'/Images/cssdesigner/themes/automobile_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/automobile-moto.jpg', thumbnailUrl:'/Images/cssdesigner/themes/automobile-moto_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/bateau.jpg', thumbnailUrl:'/Images/cssdesigner/themes/bateau_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/bijoux.jpg', thumbnailUrl:'/Images/cssdesigner/themes/bijoux_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/business.jpg', thumbnailUrl:'/Images/cssdesigner/themes/business_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/cible.jpg', thumbnailUrl:'/Images/cssdesigner/themes/cible_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/coffee.jpg', thumbnailUrl:'/Images/cssdesigner/themes/coffee_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/dance.jpg', thumbnailUrl:'/Images/cssdesigner/themes/dance_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/digital-architecture.jpg', thumbnailUrl:'/Images/cssdesigner/themes/digital-architecture_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/digital-cercle.jpg', thumbnailUrl:'/Images/cssdesigner/themes/digital-cercle_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/digital-marque-page.jpg', thumbnailUrl:'/Images/cssdesigner/themes/digital-marque-page_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/digital-page.jpg', thumbnailUrl:'/Images/cssdesigner/themes/digital-page_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/digital-rond.jpg', thumbnailUrl:'/Images/cssdesigner/themes/digital-rond_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/digital-splash.jpg', thumbnailUrl:'/Images/cssdesigner/themes/digital-splash_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/digital-tache-gris.jpg', thumbnailUrl:'/Images/cssdesigner/themes/digital-tache-gris_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/digital-tache-noir.jpg', thumbnailUrl:'/Images/cssdesigner/themes/digital-tache-noir_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/digital-tache-rose.jpg', thumbnailUrl:'/Images/cssdesigner/themes/digital-tache-rose_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/digital-vague.jpg', thumbnailUrl:'/Images/cssdesigner/themes/digital-vague_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/ecriture.jpg', thumbnailUrl:'/Images/cssdesigner/themes/ecriture_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/energie-renouvelable.jpg', thumbnailUrl:'/Images/cssdesigner/themes/energie-renouvelable_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/enfant.jpg', thumbnailUrl:'/Images/cssdesigner/themes/enfant_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/epice-bois.jpg', thumbnailUrl:'/Images/cssdesigner/themes/epice-bois_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/epice-carre.jpg', thumbnailUrl:'/Images/cssdesigner/themes/epice-carre_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/epice-fond-noir.jpg', thumbnailUrl:'/Images/cssdesigner/themes/epice-fond-noir_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/femme-mode.jpg', thumbnailUrl:'/Images/cssdesigner/themes/femme-mode_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/jardin-patchwork.jpg', thumbnailUrl:'/Images/cssdesigner/themes/jardin-patchwork_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/jardinier.jpg', thumbnailUrl:'/Images/cssdesigner/themes/jardinier_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/outils.jpg', thumbnailUrl:'/Images/cssdesigner/themes/outils_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/justice.jpg', thumbnailUrl:'/Images/cssdesigner/themes/justice_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/lingerie-sexy.jpg', thumbnailUrl:'/Images/cssdesigner/themes/lingerie-sexy_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/liseraie.jpg', thumbnailUrl:'/Images/cssdesigner/themes/liseraie_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/livre.jpg', thumbnailUrl:'/Images/cssdesigner/themes/livre_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/logo.jpg', thumbnailUrl:'/Images/cssdesigner/themes/logo_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/mannequin-liseraie.jpg', thumbnailUrl:'/Images/cssdesigner/themes/mannequin-liseraie_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/montre.jpg', thumbnailUrl:'/Images/cssdesigner/themes/montre_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/motif-fleur.jpg', thumbnailUrl:'/Images/cssdesigner/themes/motif-fleur_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/motif-losange.jpg', thumbnailUrl:'/Images/cssdesigner/themes/motif-losange_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/nappe.jpg', thumbnailUrl:'/Images/cssdesigner/themes/nappe_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/nuage.jpg', thumbnailUrl:'/Images/cssdesigner/themes/nuage_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/pancarte.jpg', thumbnailUrl:'/Images/cssdesigner/themes/pancarte_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/service-restauration.jpg', thumbnailUrl:'/Images/cssdesigner/themes/service-restauration_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/son.jpg', thumbnailUrl:'/Images/cssdesigner/themes/son_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/vetement-enfant.jpg', thumbnailUrl:'/Images/cssdesigner/themes/vetement-enfant_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/vin.jpg', thumbnailUrl:'/Images/cssdesigner/themes/vin_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/voyage.jpg', thumbnailUrl:'/Images/cssdesigner/themes/voyage_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/montagne.jpg', thumbnailUrl:'/Images/cssdesigner/themes/montagne_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/BD.jpg', thumbnailUrl:'/Images/cssdesigner/themes/BD_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/bulle.jpg', thumbnailUrl:'/Images/cssdesigner/themes/bulle_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/camouflage.jpg', thumbnailUrl:'/Images/cssdesigner/themes/camouflage_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/choc.jpg', thumbnailUrl:'/Images/cssdesigner/themes/choc_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/frise.jpg', thumbnailUrl:'/Images/cssdesigner/themes/frise_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/lotus.jpg', thumbnailUrl:'/Images/cssdesigner/themes/lotus_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/rond.jpg', thumbnailUrl:'/Images/cssdesigner/themes/rond_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/oeuf.jpg', thumbnailUrl:'/Images/cssdesigner/themes/oeuf_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/guirlande.jpg', thumbnailUrl:'/Images/cssdesigner/themes/guirlande_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/texture-metal.jpg', thumbnailUrl:'/Images/cssdesigner/themes/texture-metal_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/texture-bois.jpg', thumbnailUrl:'/Images/cssdesigner/themes/texture-bois_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/texture-pierre.jpg', thumbnailUrl:'/Images/cssdesigner/themes/texture-pierre_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/texture-platre.jpg', thumbnailUrl:'/Images/cssdesigner/themes/texture-platre_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/texture-quadrillage.jpg', thumbnailUrl:'/Images/cssdesigner/themes/texture-quadrillage_thumbnail.jpg'},
{url:'/Images/cssdesigner/themes/soleil-rouge.jpg', thumbnailUrl:'/Images/cssdesigner/themes/soleil-rouge_thumbnail.jpg'}];
}
function getPredefinedColorModel(){
	return [{colors:['7BBC0F','274A90','E8E8E8'],name:{0:'Défaut',1:'Default',2:'Défaut',3:'Défaut',4:'Défaut',5:'Défaut'}},
			{colors:['A17F7F','633434','262626'],name:{0:'Vignoble',1:'Vineyard',2:'Vignoble',3:'Vignoble',4:'Vignoble',5:'Vignoble'}},
			{colors:['99B3CC','434C69','858A99'],name:{0:'Stone Cold',1:'Stone Cold',2:'Stone Cold',3:'Stone Cold',4:'Stone Cold',5:'Stone Cold'}},
			{colors:['8F0401','2B0000','ABABAB'],name:{0:'Rubis',1:'Ruby',2:'Rubis',3:'Rubis',4:'Rubis',5:'Rubis'}},
			{colors:['0C536B','117B9E','CCE0E6'],name:{0:'Turquoise',1:'Turquoise',2:'Turquoise',3:'Turquoise',4:'Turquoise',5:'Turquoise'}},
			{colors:['BD9664','613D0F','E6D8C8'],name:{0:'Wood',1:'Wood',2:'Wood',3:'Wood',4:'Wood',5:'Wood'}},
			{colors:['1F5B94','387BC2','2D3540'],name:{0:'Saphir',1:'Sapphire',2:'Saphir',3:'Saphir',4:'Saphir',5:'Saphir'}},
			{colors:['4F1D1D','8C1F1F','402D2D'],name:{0:'Rhésus',1:'Rhesus',2:'Resus',3:'Resus',4:'Resus',5:'Resus'}},
			{colors:['9EB81F','2E8239','7F960C'],name:{0:'Thé vert',1:'Green Tea',2:'Thé vert',3:'Thé vert',4:'Thé vert',5:'Thé vert'}},
			{colors:['FFE7CC','FAA507','FFBB00'],name:{0:'Karma',1:'Karma',2:'Karma',3:'Karma',4:'Karma',5:'Karma'}},
			{colors:['CCA5C9','780D44','FFF0FD'],name:{0:'Pourpre',1:'Purple Rain',2:'Pourpre',3:'Pourpre',4:'Pourpre',5:'Pourpre'}},
			{colors:['b0b0b0','A10808','000000'],name:{0:'FeelGood',1:'FeelGood',2:'FeelGood',3:'FeelGood',4:'FeelGood',5:'FeelGood'}},
			{colors:['FFD200','991F66','4D0830'],name:{0:'Cocktail',1:'Cocktail',2:'Cocktail',3:'Cocktail',4:'Cocktail',5:'Cocktail'}},
			{colors:['211E12','D15B1F','ADADAD'],name:{0:'Orange Skark',1:'Orange Skark',2:'Orange Skark',3:'Orange Skark',4:'Orange Skark',5:'Orange Skark'}},
			{colors:['000000','D9D9D9','000000'],name:{0:'Fat Domino',1:'Fat Domino',2:'Fat Domino',3:'Fat Domino',4:'Fat Domino',5:'Fat Domino'}},
			{colors:['824642','B8795A','858069'],name:{0:'London',1:'London',2:'London',3:'London',4:'London',5:'London'}},
			{colors:['425782','9C629C','3E2859'],name:{0:'Methyl',1:'Methyl',2:'Methyl',3:'Methyl',4:'Methyl',5:'Methyl'}},
			{colors:['824254','FFFFFF','FFD780'],name:{0:'Sand',1:'Sand',2:'Sand',3:'Sand',4:'Sand',5:'Sand'}},
			{colors:['F5CAC6','BD1E1E','D6C1C1'],name:{0:'Sweet pastel',1:'Sweet Cherry',2:'Sweet pastel',3:'Sweet pastel',4:'Sweet pastel',5:'Sweet pastel'}},
			{colors:['07133D','2D2294','27282E'],name:{0:'Dark age',1:'Dark Age',2:'Dark age',3:'Dark age',4:'Dark age',5:'Dark age'}},
			{colors:['DEE0E0','000000','DEE0E0'],name:{0:'Fog',1:'Fog',2:'Fog',3:'Fog',4:'Fog',5:'Fog'}}];
}

function oxToolbar(){
	this.groups = [];
}
oxToolbar.prototype = {
	addGroup:function(conf){
		this.groups.push(conf);
	},
	getGroups:function(){
		return this.groups;
	}
}
function uiModel(){
	this.init = false;
	this.models = [];
}
uiModel.prototype ={
	add:function(model){
		this.models.push(model);
	},
	initialize: function(){
		if (this.init){
			return;
		}
		var models=this.models, modelCount = models.length;
		for(var modelIdx=0; modelIdx < modelCount; modelIdx++){
			var model = models[modelIdx];
			//if (window.console)console.log('before calling model.init');
			model.init();
		}
		this.init = true;
	},
	reset: function(){
		if (this.init){
			var models=this.models, modelCount = models.length;
			for(var modelIdx=0; modelIdx < modelCount; modelIdx++){
				var model = models[modelIdx];
				model.reset();
			}
		}
	}
}
function propertyModel(){
	this.read = false;
	this.properties = [];
}
propertyModel.prototype ={
	add:function(property){
		this.properties.push(property);
	},
	readFromStyleSheet: function(){
		if (this.read){
			return;
		}
		var properties=this.properties, propCount = properties.length;
		for(var propIdx=0; propIdx < propCount; propIdx++){
			var prop = properties[propIdx];
			prop.readStyleSheet();
			prop.publish();
		}
		this.read = true;
	},
	reset: function(){
		if (this.read){
			var properties=this.properties, propCount = properties.length;
			for(var propIdx=0; propIdx < propCount; propIdx++){
				properties[propIdx].reset();
			}
		}
	}
}
function designerConf(){
	this.lang = 0;
	this.toolbar = new oxToolbar();
	this.propertyModel = new propertyModel();
	this.uiModel = new uiModel();
}
designerConf.prototype = {
	setToolbarRenderer: function(rndr){
		this.toolbarRndr = rndr;
	},
	renderToolbar: function(){
		if (this.toolbarRndr){
			if (this.toolbarRndr instanceof Function){
				this.toolbarRndr.call(null, this);
			} else {
				this.toolbarRndr.render(this);
			}
		}
	},
	setColorModel: function(model){
		this.colorModel = model;
		if (this.colorModel && !this.colorModel.model){
			//if (window.console) console.log('setColorModel init model');
			this.colorModel.predefinedColorModel = getPredefinedColorModel();
		}
	},
	getColorModel: function(){
		return this.colorModel;
	},
	createStyleMgr: function(){
		return new styleMgr();
	},
	formatCSSConf: function(){
		var cssConf = this.cssConf;
		var cssPropertyList, splitdSelectorName, formattedCSSConf = {};
		this.srcCssConf = cssConf;
		this.cssConf = formattedCSSConf;
		for (var selectorText in cssConf){
			var lowerCaseSelectorText = selectorText.toLowerCase();
			var splitdSelector = lowerCaseSelectorText.split(','), splitdSelectorCount = splitdSelector.length;
			formattedCSSConf[lowerCaseSelectorText] = cssConf[selectorText];
			if (splitdSelectorCount > 1){
				//if (window.console) console.group('selectorText:[' + selectorText + ']');
				for (var splitdSelectorIdx = 0; splitdSelectorIdx < splitdSelectorCount; splitdSelectorIdx++){
					splitdSelectorName = splitdSelector[splitdSelectorIdx].trim();
					splitdSelectorCSSProperties = formattedCSSConf[splitdSelectorName];
					if (splitdSelectorCSSProperties){
						var cssProperties = cssConf[selectorText];
						for (var cssPropertyName in cssProperties){
							var propValue = splitdSelectorCSSProperties[cssPropertyName];
							if (propValue){
								alert('ERROR RESETING A PROPERTY VALUE THAT ALREADY EXIST\n\nselector:[' + splitdSelectorName + '] cssPropertyName:[' + cssPropertyName + ']');
							} else {
								splitdSelectorCSSProperties[cssPropertyName] = cssProperties[cssPropertyName];
							}
						}
					} else {
						//if (window.console) console.log('splitdSelectorName:[' + splitdSelectorName + ']');
						formattedCSSConf[splitdSelectorName] = cssConf[selectorText];
					}
				}
				//if (window.console) console.groupEnd();
			}
		}
	},
	linkPropertiesToCSS: function(){
		var strLinkHRef=null, cssConf = this.cssConf;
		var nRuleIdx=0, cssRule=null, styleSheet, rules, selectorText, cssProperties, style;
		var styleSheets = getStyleSheets();
		if (!styleSheets || !cssConf) {
			//if (window.console) console.log('linkPropertiesToCSS !styleSheets || !cssConf');
			return;
		}
		for (selectorText in cssConf){
			cssProperties = cssConf[selectorText];
			if (cssProperties){
				for(var cssProperty in cssProperties){
					var property = cssProperties[cssProperty];
					if (property && property.styleMgr){
						property.styleMgr().reset();
					}
				}
			}
		}

		//var doc = getIFrameDoc();

		var nStyleSheetCount = styleSheets.length;
		for (var nStyleSheetIdx=nStyleSheetCount-1; nStyleSheetIdx >=0; nStyleSheetIdx--) {
			styleSheet=styleSheets[nStyleSheetIdx];
			rules = null;
			strLinkHRef = styleSheet.href;
			if (strLinkHRef){
				strLinkHRef = strLinkHRef.toLowerCase();
				if (strLinkHRef.indexOf('designcss') > -1){
					try{
						rules = styleSheet.cssRules ? styleSheet.cssRules : styleSheet.rules;
					} catch(e){
						if (window.console) console.log('unexpected exception', e);
						rules = null;
					}
				}
			}
			if (!rules){
				continue;
			}
			nRuleIdx=0
			do {
				cssRule = rules[nRuleIdx];
				if (cssRule){
					selectorText = cssRule.selectorText.toLowerCase();
					if (selectorText) {
						cssProperties = cssConf[selectorText];
						if (cssProperties){
							var relDOMElem = null;
							//if (selectorText.indexOf(':') == -1){
								//relDOMElem = $(selectorText, doc);
								//if (window.console) console.log(cssRule.selectorText, relDOMElem.length);
								//if (relDOMElem.length > 0){
								//	alert(cssRule.selectorText);
								//}
							//}
							for(var cssProperty in cssProperties){
								var property = cssProperties[cssProperty];
								if (property && property.styleMgr){

									var camelized = cssProperty.camelize();
									var styleValue = cssRule.style[camelized];
									var undef;

									if ((styleValue == null) || (styleValue == undef)){
										if (camelized == 'float'){
											var newPropName = 'cssFloat';
											//if (window.console) console.log('unable to find "', camelized, '" CSSProperty => trying "', newPropName ,'" for', selectorText);
											camelized = newPropName;
											styleValue = cssRule.style[newPropName];

											if ((styleValue == null) || (styleValue == undef)){
												newPropName = 'styleFloat';
												//if (window.console) console.log('unable to find "', camelized, '" CSSProperty => trying "', newPropName ,'" for', selectorText);
												camelized = newPropName;
												styleValue = cssRule.style[newPropName];
											}
										} else if (camelized == 'opacity'){
											//IE does not support the opacity style property
											//opacity: 0.4; => filter: alpha(opacity=40)
											var newPropName = 'filter';
											//if (window.console) console.log('unable to find "', camelized, '" CSSProperty => trying "', newPropName ,'" for', selectorText);
											camelized = newPropName;
											styleValue = cssRule.style[newPropName];
											if (styleValue){
												var codec = property.codec, opacityCodec = new IEOpacityCodec();
												if (!codec){
													property.codec = opacityCodec;
												} else if (codec instanceof codecList){
													codec.codecs.push(opacityCodec);
												} else if (property.codec instanceof Object){
													property.codec = new codecList([codec, opacityCodec]);
												}
											}
										}
									}

									if ((styleValue == null) || (styleValue == undef)){
										if (window.console) console.log('Failed to add style for ', selectorText, ' : ', camelized);
									} else {
										property.styleMgr().add(camelized, cssRule, relDOMElem);
									}
								}
							}
						}
					}
				}
				nRuleIdx++;
			} while (cssRule)
		}

		//if (window.console) console.log('before propertyModel.readFromStyleSheet');
		if (this.propertyModel){
			this.propertyModel.readFromStyleSheet();
		}
		if (this.uiModel){
			this.uiModel.initialize();
		}
		return null;
	},
	applyCSSProperties: function(){
		if (!this.cssConf){
			return;
		}
		var selectorText, cssProperties, cssConf=this.cssConf;
		for (selectorText in cssConf){
			cssProperties = cssConf[selectorText];
			if (cssProperties){
				for(var cssProperty in cssProperties){
					var property = cssProperties[cssProperty];
					if (property && property.styleMgr){
						property.apply();
					}
				}
			}
		}
	},
	setCssVar: function(cssvar){
		this.cssvar = cssvar;
	},
	setCssConf: function(cssConf){
		this.cssConf = cssConf;
		if (false){
			for (var selectorText in cssConf){
				var cssProperties = cssConf[selectorText];
				for (var cssPropertyName in cssProperties){
					var property = cssProperties[cssPropertyName];
					if (property && property.debugAddCSSProp){
						property.debugAddCSSProp(selectorText, cssPropertyName);
					}
				}
			}
		}
	},
	setDesignConf: function(conf){
		if (conf.account){
			this.account = conf.account;
		}
		if (conf.design){
			this.design = conf.design;
		}
		if (conf.lang){
			this.lang = conf.lang;
		}
		if (conf.src){
			this.src = conf.src;
		}
		if (conf.toolbarRenderer){
			this.setToolbarRenderer(conf.toolbarRenderer);
		}
	}
}
cssDesignerConf = new designerConf();

function getStyleSheets(){
	return iframeStyleSheets;
}

function rgb2hsl(rgb) {
	if (!rgb){
		return null;
	}
	var min, max, delta, h, s, l;
	var r = rgb[0]/255, g = rgb[1]/255, b = rgb[2]/255;
	min = Math.min(r,g,b);
	max = Math.max(r,g,b);
	delta = max - min;
	l = (min + max) / 2;
	s = 0;
	if (l > 0 && l < 1) {
		s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l));
	}
	h = 0;
	if (delta > 0) {
		if (max == r && max != g) h += (g - b) / delta;
		if (max == g && max != b) h += (2 + (b - r) / delta);
		if (max == b && max != r) h += (4 + (r - g) / delta);
		h /= 6;
	}
	return {0:h,1:s,2:l};
}
function rgb2hsv(rgb) {
	var max=Math.max(rgb[0],rgb[1],rgb[2]), delta=max-Math.min(rgb[0],rgb[1],rgb[2]), H, S, V;
	if(max!=0) {
		S=Math.round(delta/max*100);
		if(rgb[0]==max) H=(rgb[1]-rgb[2])/delta;
		else if(rgb[1]==max) H=2+(rgb[2]-rgb[0])/delta;
		else if(rgb[2]==max) H=4+(rgb[0]-rgb[1])/delta;
		H=Math.min(Math.round(H*60),360);
		if(H<0) H+=360;
	}
	return({0:H?H:0,1:S?S:0,2:Math.round((max/255)*100)});
}
function hsv2rgb(r){
	var F, R, B, G, H=r[0]/360, S=r[1]/100, V=r[2]/100;
	if(S>0) {
		if(H>=1) H=0;
		H=6*H;
		F=H-Math.floor(H);
		A=Math.round(255*V*(1-S));
		B=Math.round(255*V*(1-(S*F)));
		C=Math.round(255*V*(1-(S*(1-F))));
		V=Math.round(255*V);
		switch(Math.floor(H)) {
			case 0: R=V; G=C; B=A; break;
			case 1: R=B; G=V; B=A; break;
			case 2: R=A; G=V; B=C; break;
			case 3: R=A; G=B; B=V; break;
			case 4: R=C; G=A; B=V; break;
			case 5: R=V; G=A; B=B; break;
		}
		return([R?R:0,G?G:0,B?B:0]);
	}
	else return([(V=Math.round(V*255)),V,V]);
}
/*
function hex2rgb(r){
	if (r.charAt(0)=='#') {
		r = r.substr(1);
	}
	var red, green, blue;
	if (r.length == 3) {
		red = r.substr(0,1);
		red+=red;
		green = r.substr(1,1);
		green+=green;
		blue = r.substr(2,1);
		blue+=blue;
	} else {
		red = r.substr(0,2);
		green = r.substr(2,2);
		blue = r.substr(4,2);
	}
	return({0:parseInt(red,16),1:parseInt(green,16),2:parseInt(blue,16)});
}
*/
function hex2rgb(color){
	if (!color){
		return null;
	}
	var red, green, blue, len = color.length;
	if (len == 7) {
		red = color.substr(1, 2);
		green = color.substr(3, 2);
		blue = color.substr(5, 2);
	}
	else if (len == 6) {
		red = color.substr(0, 2);
		green = color.substr(2, 2);
		blue = color.substr(4, 2);
	}
	else if (len == 4) {
		red = color.substr(1, 2);
		green = color.substr(3, 2);
		blue = color.substr(5, 2);
	}
	else if (len == 3) {
		red = color.substr(0, 1);
		green = color.substr(1, 1);
		blue = color.substr(2, 1);
	}
	return({0:parseInt(red,16),1:parseInt(green,16),2:parseInt(blue,16)});
}
function codecList(codecs){
	this.codecs = codecs;
}
codecList.prototype = {
	encode: function(value){
		var newVal, codecs = this.codecs, codecCount = codecs.length;
		for (var codecIdx = 0; codecIdx < codecCount; codecIdx++){
			newVal = codecs[codecIdx].encode(value);
			//if (window.console) console.log('codecList encode :', value, ' to ', newVal);
			value = newVal;
		}
		return value;
	},
	decode: function(value){
		var newVal, codecs = this.codecs, codecUBound = codecs.length - 1;
		for (var codecIdx = codecUBound; codecIdx > -1; codecIdx--){
			newVal = codecs[codecIdx].decode(value);
			//if (window.console) console.log('codecList decode :', value, 'to ', newVal);
			value = newVal;
		}
		return value;
	}
}
function IEOpacityCodec(){
}
IEOpacityCodec.prototype={
	encode: function(value){
		//0.4 to 'alpha(opacity=40)'
		return 'alpha(opacity=' + Math.floor(value * 100) + ')';
	},
	decode: function(value){
		//'alpha(opacity=40)' to 0.4
		var result=0, equalIdx = value.indexOf('=');
		if (equalIdx >= 0){
			value = value.substr(equalIdx+1);
			result = parseInt(value);
			result /= 100;
		}
		return result;
	}
}

function prefixSuffixCodec(prefix, suffix){
	this.prefix = prefix;
	if (prefix){
		this.prefixLen = prefix.length;
	}
	this.suffix = suffix;
	if (suffix){
		this.suffixLen = suffix.length;
	}
}
prefixSuffixCodec.prototype = {
	encode: function(value){
		var result = '';
		if (this.prefix){
			result += this.prefix;
		}
		result += value;
		if (this.suffix){
			result += this.suffix;
		}
		//if (window.console) console.log('prefixSuffixCodec encode :', value, ' to ', result);
		return result;
	},
	decode: function(value){
		var result;
		if (!value){
			return null;
		}
		result = value;
		if (!(value instanceof String)){
			result = value.toString();
		}
		if (this.prefix){
			if (result.substr(0, this.prefixLen) == this.prefix){
				result = result.substr(this.prefixLen);
			}
		}
		if (this.suffix){
			var valueLen = result.length;
			if (result.substr(valueLen - this.suffixLen) == this.suffix){
				result = result.substr(0, valueLen - this.suffixLen);
			}
		}
		//if (window.console) console.log('prefixSuffixCodec decode :', value, ' to ', result);
		return result;
	}
}
function createPrefixSuffixCodec(prefix, suffix){
	return new prefixSuffixCodec(prefix, suffix);
}
function bgUrlCodec(){
	this.innerCodec = new codecList([createPrefixSuffixCodec('"', '"'), createPrefixSuffixCodec('url(', ')')])
}
bgUrlCodec.prototype = {
	encode: function(value){
		if (!value){
			value = 'none';
		} else if (value.length == 0){
			value = 'none';
		} else if (value != 'none'){
			value = this.innerCodec.encode(value);
		}
		return value;
	},
	decode: function(value){
		var result = '';
		if (value == 'none'){
		} else if (value.length == 0){
		} else if (value != 'none'){
			result = this.innerCodec.decode(value);
		}
		return result;
	}
}
function colorCodec(){
}
colorCodec.prototype = {
	colorDefs: [
		{
			re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
			process: function (bits){
				return [
					parseInt(bits[1]),
					parseInt(bits[2]),
					parseInt(bits[3])
				];
			}
		},
		{
			re: /^(\w{2})(\w{2})(\w{2})$/,
			process: function (bits){
				return [
					parseInt(bits[1], 16),
					parseInt(bits[2], 16),
					parseInt(bits[3], 16)
				];
			}
		},
		{
			re: /^(\w{1})(\w{1})(\w{1})$/,
			process: function (bits){
				return [
					parseInt(bits[1] + bits[1], 16),
					parseInt(bits[2] + bits[2], 16),
					parseInt(bits[3] + bits[3], 16)
				];
			}
		}
	],
	encode: function(value){
		if (!value){
			return value;
		}
		return '#' + value;
	},
	decode: function(value){
		var r, g, b;
		if (!value){
			return null;
		}
		if (!(value instanceof String)){
			value = value.toString();
		}
		if (value.charAt(0) == '#'){
			value = value.substr(1,6);
		}
		value = value.replace(/ /g,'');
		value = value.toLowerCase();

		var colorDefs = this.colorDefs;
		var colorDefCount = this.colorDefs.length;
		for (var colorDefIdx = 0; colorDefIdx < colorDefCount; colorDefIdx++) {
			var re = colorDefs[colorDefIdx].re;
			var processor = colorDefs[colorDefIdx].process;
			var bits = re.exec(value);
			if (bits) {
				var channels = processor(bits);
				r = channels[0];
				g = channels[1];
				b = channels[2];
			}
		}
		// validate/cleanup values
		r = (r < 0 || isNaN(r)) ? 0 : ((r > 255) ? 255 : r);
		g = (g < 0 || isNaN(g)) ? 0 : ((g > 255) ? 255 : g);
		b = (b < 0 || isNaN(b)) ? 0 : ((b > 255) ? 255 : b);

		r = r.toString(16).toUpperCase();
		g = g.toString(16).toUpperCase();
		b = b.toString(16).toUpperCase();
		if (r.length == 1) r = '0' + r;
		if (g.length == 1) g = '0' + g;
		if (b.length == 1) b = '0' + b;
		return r + g + b;
	}
}
function createCodecList(codec, prefix, suffix){
	if (prefix || suffix){
		codec = new codecList([codec, createPrefixSuffixCodec(prefix, suffix)]);
	}
	return codec;
}
function createLookUpCodec(cssValues, uiValues, prefix, suffix){
	return createCodecList(new lookUpCodec(cssValues, uiValues), prefix, suffix);
}
function lookUpCodec(cssValues, uiValues){
	this.count = cssValues.length;
	this.cssValues = cssValues;
	this.uiValues = uiValues;
}
lookUpCodec.prototype = {
	encode: function(value){
		var count=this.count, uiValues=this.uiValues;
		for (var idx=0; idx<count; idx++){
			if (uiValues[idx]==value){
				return this.cssValues[idx];
			}
		}
		return this.cssValues[0];
	},
	decode: function(value){
		var count=this.count, cssValues=this.cssValues;
		for (var idx=0; idx<count; idx++){
			if (cssValues[idx]==value){
				return this.uiValues[idx];
			}
		}
		return this.uiValues[0];
	}
}

function createColorCodec(prefix, suffix){
	return createCodecList(new colorCodec(), prefix, suffix);
}

function intCodec(){
}
intCodec.prototype = {
	encode: function(value){
		var returnValue = ''+value;
		//if (window.console) console.log('intCodec encode :', value, ' to ', returnValue);
		return returnValue;
	},
	decode: function(value){
		returnValue = parseInt(value);
		//if (window.console) console.log('intCodec encode :', value, 'to ', returnValue);
		return returnValue;
	}
}
function createIntCodec(prefix, suffix){
	return createCodecList(new intCodec(), prefix, suffix);
}
function noopCodec(){
}
noopCodec.prototype = {
	encode: function(value){
		return value;
	},
	decode: function(value){
		return value;
	}
}
var noopCodecSingleton = null;
function createNoopCodec(){
	if (noopCodecSingleton){
		return noopCodecSingleton;
	}
	noopCodecSingleton = new noopCodec();
	return noopCodecSingleton;
}
function styleMgr(){
	this.styles = [];
	this.dirty = false;
}
styleMgr.prototype = {
	useInlineStyle: false,
	add: function(cssPropertyName, cssRule, relDOMElem){
		this.styles.push({name:cssPropertyName, style:cssRule.style, dom:relDOMElem, cssname:cssPropertyName});
	},
	reset: function(){
		var len = this.styles.length;
		while (len){
			this.styles.pop();
			len--;
		}
	},
	setUseInlineStyle: function(bUseInlineStyle){
		if (styleMgr.useInlineStyle && !bUseInlineStyle){
			this.setStyles('');
		}
		styleMgr.useInlineStyle = bUseInlineStyle;
		//if (window.console) console.log('useInlineStyle', styleMgr.useInlineStyle);
	},
	setStyles: function(value){
		var styles = this.styles;
		var styleCount = styles.length;
		//if (window.console) console.log(styleCount);
		if (styleCount) this.dirty = true;
		for (var styleIdx = 0; styleIdx < styleCount; styleIdx++){
			var prop = styles[styleIdx];

			if (styleMgr.useInlineStyle){
				if (prop.dom) $(prop.dom).css(prop.cssname, value);
			} else {
				//if (window.console) console.log('prop.name', prop.name, 'value', value);
				try{
					prop.style[prop.name] = value;
				} catch(e){
					if (window.console) console.log('unexpected exception:', e.name, 'Error message:', e.message);
				}
			}
		}
	},
	read: function(){
		var value = null;
		//if (window.console) console.log('styleCount:', this.styles.length);
		if (this.styles.length > 0){
			var prop = this.styles[0];
			value = prop.style[prop.name];
			//if (window.console) console.log('styleMrg Read',prop.name, '=', value);
			if (value && !(value instanceof String)){
				value = value.toString();
				//if (window.console) console.log('styleMrg Read not a string',prop.name, '=', value);
			}
		}
		return value;
	}
}
function constOffset(value){
	this.value = value;
}
constOffset.prototype = {
	run: function(value){
		return value + this.value;
	}
}

function hsvOffset(h, s, v){
	this.h = h;
	this.s = s;
	this.v = v;
}
hsvOffset.prototype = {
	hexChars: '0123456789ABCDEF',
	run: function(value){
		if (!value){
			return null;
		}
		var hsv = rgb2hsv(hex2rgb(value));
		if (this.h){
			hsv[0] = this.safeAdd(hsv[0], this.h, 360);
		}
		if (this.s){
			hsv[1] = this.safeAdd(hsv[1], this.s, 100);
		}
		if (this.v){
			hsv[2] = this.safeAdd(hsv[2], this.v, 100);
		}
		return this.rgb2hex(hsv2rgb(hsv));
	},
	safeAdd: function(value, offset, max){
		value += offset;
		while (value < 0){
			value += max;
		}
		if (value > max) value %= max;
		return value;
	},
	toHex: function(v){
		v=Math.round(Math.min(Math.max(0,v),255));
		return(this.hexChars.charAt((v-v%16)/16)+this.hexChars.charAt(v%16));
	},
	rgb2hex: function(r){
		return(this.toHex(r[0])+this.toHex(r[1])+this.toHex(r[2]));
	}
}
function textColorOffset(vLimit, textColorForDark, textColorForBright){
	this.vLimit = vLimit;
	this.textColorForDark = textColorForDark;
	this.textColorForBright = textColorForBright;
}
textColorOffset.prototype = {
	run: function(value){
		var hsl = rgb2hsl(hex2rgb(value));
		return (hsl && (hsl[2] >= this.vLimit)) ? this.textColorForBright : this.textColorForDark;
	}
}
function darkOffset(lLimit){
	this.lLimit = lLimit;
	this.colorHelper = new colorHelper();
}
darkOffset.prototype = {
	run: function(value){
		var hsl=[],rgb=[],clrHelper = this.colorHelper;
		clrHelper.hex2rgb(value, rgb);
		clrHelper.rgb2hsl(rgb,hsl);
		if (hsl[2] >= this.lLimit){
			hsl[2] = this.lLimit;
		}
		clrHelper.hsl2rgb(hsl,rgb);
		return clrHelper.rgb2hex(rgb);
	}
}
function lightOffset(lLimit){
	this.lLimit = lLimit;
	this.colorHelper = new colorHelper();
}
lightOffset.prototype = {
	run: function(value){
		var hsl=[],rgb=[],clrHelper = this.colorHelper;
		clrHelper.hex2rgb(value, rgb);
		clrHelper.rgb2hsl(rgb,hsl);
		if (hsl[2] <= this.lLimit){
			hsl[2] = this.lLimit;
		}
		clrHelper.hsl2rgb(hsl,rgb);
		return clrHelper.rgb2hex(rgb);
	}
}
function createConstOffsetProperty(property, offset){
	return new stdProperty({linkedTo: property, linkOffset: offset});
}
function stdProperty(config){
	this.linkedProps = [];
	this.linkedPropCount = 0;
	this.listeners = [];
	this.dirty = false;
	this.init = false;
	if (!config){
		this.codec = createNoopCodec();
		this.linkedStyles = cssDesignerConf.createStyleMgr();
		return;
	}
	if (config.styleMgr){
		this.linkedStyles = config.styleMgr;
	} else {
		this.linkedStyles = cssDesignerConf.createStyleMgr();
	}
	this.copyInitProps(config);
	if (config.linkedTo){
		/*
		var linkedTo = config.linkedTo;
		if (config.linkOffset){
			if (config.linkOffset instanceof Object){
				this.linkOffset = config.linkOffset;
			} else {
				this.linkOffset = new constOffset(config.linkOffset);
			}
		}
		linkedTo.addLinkedProp(this);
		if (linkedTo.codec){
			if (this.codec){
				this.codec = new codecList([linkedTo.codec, this.codec]);
			} else {
				this.codec = linkedTo.codec;
			}
		}
		*/
		var linkedTo = config.linkedTo,
			link = {prop:this};
		if (config.linkOffset){
			if (config.linkOffset instanceof Object){
				link.offset = config.linkOffset;
			} else {
				link.offset = new constOffset(config.linkOffset);
			}
			this.linkOffset = link.offset;
		}
		linkedTo.addLinkedProp(link);
		if (linkedTo.codec){
			if (this.codec){
				this.codec = new codecList([linkedTo.codec, this.codec]);
			} else {
				this.codec = linkedTo.codec;
			}
		}
	}
	if (!this.codec){
		this.codec = createNoopCodec();
	}
}
stdProperty.prototype = {
	initProps:['defaultValue','minValue','maxValue','codec','change'],
	copyInitProps:function(config){
		var initProps=this.initProps, propCount=initProps.length;
		var me=this, prop;
		for (propIdx=0; propIdx<propCount; propIdx++){
			prop=initProps[propIdx];
			me[prop] = config[prop];
		}
	},
	startValueSet: function(){
		//this.linkedStyles.setUseInlineStyle(true);
	},
	stopValueSet: function(){
		//this.linkedStyles.setUseInlineStyle(false);
		//this.setValue(this.value);
	},
	refreshLinkedProps: function(){
		var linkedProps = this.linkedProps,
			linkedPropCount = this.linkedPropCount, link;
		if (linkedPropCount){
			var offsetValue;
			for (var linkedPropIdx = 0; linkedPropIdx < linkedPropCount; linkedPropIdx++){
				link = linkedProps[linkedPropIdx];
				if (link){
					offsetValue = this.value;
					if (link.offset){
						offsetValue = link.offset.run(offsetValue);
					}
					link.prop.setLinkedValue(this.codec.encode(offsetValue));
					//link.prop.setValue(offsetValue);
				}
			}
		}
	},
	privateSetValue: function(value, checkLink, updateDirty){
		var dirty = false, newValue = this.codec.decode(value);
		if (checkLink && this.linkOffset){
			newValue = this.linkOffset.run(newValue);
			//if (window.console) console.log(this.debugGetName(), 'linkOffset(', value, ',',checkLink, ',',updateDirty,')', newValue);
		}
		if (this.change){
			newValue = this.change.call(this, newValue, value);
		}
		if (this.value != newValue){
			//if (window.console) console.log(this.debugGetName(), 'privateSetValue(', value, ',',checkLink, ',',updateDirty,')', this.value, newValue, (this.value != newValue), checkLink);
			if (updateDirty) this.dirty = true;
			this.value = newValue;
			this.refreshLinkedProps();
			this.publish();
			this.apply();
		}
	},
	setLinkedValue: function(value){
		//if (window.console) console.log('setLinkedValue', value);
		this.privateSetValue(value, false, true);
	},
	setValue: function(value){
		//if (window.console) console.log('setValue', value);
		this.privateSetValue(value, true, true);
	},
	publish: function(){
		var listeners = this.listeners;
		var listenerCount = listeners.length;
		for (var listenerIdx = 0; listenerIdx < listenerCount; listenerIdx++){
			var valueChanged = listeners[listenerIdx];
			if (valueChanged){
				valueChanged(this);
			}
		}
	},
	addListener: function(listener){
		var toAdd = listener;
		if (toAdd instanceof Function){
		} else if (toAdd instanceof Object){
			toAdd = function(property){
				listener.valueChanged(property);
			}
		}
		this.listeners.push(toAdd);
	},
	valueChanged: function(listener){
		this.listeners.push(listener);
	},
	apply: function(){
		if (this.dirty){
			this.linkedStyles.setStyles(this.toString());
		}
	},
	styleMgr: function(){
		return this.linkedStyles;
	},
	/*
	addLinkedProp: function(prop){
		this.linkedProps.push(prop);
		this.linkedPropCount = this.linkedProps.length;
	},*/
	addLinkedProp: function(link){
		this.linkedProps.push(link);
		this.linkedPropCount = this.linkedProps.length;
	},
	isDirty: function(){
		return this.dirty;
	},
	setDirty: function(dirty){
		this.dirty = dirty;
	},
	readStyleSheet: function(){
		if (!this.init){
			this.init = true;
			//if (window.console) console.log(this.debugGetName(), 'readStyleSheet stylesheet');
			var value = this.linkedStyles.read();
			//if (window.console) console.log(this.debugGetName(), 'readStyleSheet stylesheet value',value);
			if (!value){
				if (!this.defaultValue){
					return null;
				}
				this.value = this.defaultValue;
			}
			this.originalValue = value;
			this.value = this.codec.decode(value);
			//if (window.console) console.log(this.debugGetName(), 'readStyleSheet decoded value:', this.value, 'stylesheet value',value);
		}
		return this.value;
	},
	reset:function(){
		//if (window.console) console.log('reset', value);
		if (this.dirty){
			this.privateSetValue(this.originalValue, false, false);
		}
		this.dirty = false;
	},
	toString: function(){
		return this.codec.encode(this.value);
	},
	getValue: function(){
		var result = this.value;
		if (!this.init){
			result = this.readStyleSheet();
			//if (window.console) console.log('init called within getValue', result);
		}
		return result;
	},
	debugAddCSSProp: function(selectorText, cssPropertyName){
		var cssProperties = this.cssProperties;
		if(!cssProperties){
			cssProperties = [];
			this.cssProperties = cssProperties;
		}
		cssProperties.push('['+selectorText+'{'+cssPropertyName+'}]');
	},
	debugGetName: function(){
		var cssProperties = this.cssProperties;
		if(!cssProperties){
			return '[none]';
		}
		return cssProperties.join('');
	}
}

function onUnloadFrame(){
	//if (window.console) console.log('unload');
	dirty = true;
	doLink = true;
}
function getIFrameDoc(){
	var iframe = window.frames['WebSitePreview'];
	var doc = iframe.contentWindow || iframe.contentDocument || iframe.document;
	if (doc && doc.document) {
		doc = doc.document;
	}
	return doc;
}
function onFrameLoaded(){
	registerIFrameListener();
	//if (window.console) console.log('load');
	var doc = getIFrameDoc();
	if (doc){
		iframeStyleSheets = doc.styleSheets;
	}
	if (doLink){
		cssDesignerConf.linkPropertiesToCSS();
		doLink = false;
	}
	if (cssDesignerConf && dirty && initDone){
		cssDesignerConf.applyCSSProperties();
		dirty = false;
	}
}
function registerIFrameListener(){
	var frame = frames['WebSitePreview'];
	if(frame.attachEvent){
		frame.attachEvent('onunload', onUnloadFrame);
	} else if (frame.addEventListener){
		frame.addEventListener('unload', onUnloadFrame, false);
	}
}
if (!String.prototype.trim){
	String.prototype.trimRegExp = /(?:^\s+|\s+$)/g;
	String.prototype.trim = function(){
		return this.replace(this.trimRegExp, '');
	}
}
if (!String.prototype.camelize){
	String.prototype.camelize = function(){
		var parts = this.split('-'), len = parts.length;
		if (len == 1) {
			return parts[0];
		}
		var camelized = this.charAt(0) == '-' ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1) : parts[0];
		for (var i = 1; i < len; i++){
			camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
		}
		return camelized;
	}
}

function showWebSitePreviewOverlay(){
	if (webSitePreviewOverlay && webSitePreview){
		var offset = webSitePreview.offset();
		webSitePreviewOverlay.css({display:'block',position:'absolute',width:webSitePreview.width()+'px',height:webSitePreview.height()+'px',left:offset.left+'px',top:offset.top+'px'});
	}
}
function hideWebSitePreviewOverlay(){
	if (webSitePreviewOverlay){
		webSitePreviewOverlay.css('display','none');
	}
}

$(function() {
	var buttons=[];

	var designerStrRes = designerStringRes[cssDesignerConf.lang];

	cssDesignerConf.strRes = designerStringRes;

	if (cssDesignerConf.account){
		$('<div id="errordialog" style="display:none;"><div class="ui-state-error ui-corner-all"><p><span style="float: left; margin-right: 0.3em;" class="ui-icon ui-icon-alert"></span><span class="msg"></span></p></div></div>').appendTo('body');
		$('<div id="successdialog" style="display:none;"><p><span class="msg"></span></p></div>').appendTo('body');
		var errDialog = $('#errordialog'), successDialog=$('#successdialog');

		function askForConfirm(dlgTitle, text, fnOnOK){
			var msg = $('.msg', successDialog), dlgButtons={};
			msg.text(text);
			successDialog.css('display', 'block');
			dlgButtons[designerStrRes.cancelBtn] = function() {
				successDialog.css('display', 'none');
				successDialog.dialog('destroy');
			};
			dlgButtons['Ok'] = function() {
				successDialog.css('display', 'none');
				successDialog.dialog('destroy');
				fnOnOK();
			};
			successDialog.dialog({
				autoOpen: true,
				closeOnEscape: true,
				bgiframe: true,
				modal: true,
				resizable: false,
				title:dlgTitle,
				buttons: dlgButtons
			});
		}
		function exitFromSmartSkins(dlgTitle, text, fnOnSave, fnOnExit) {
			var msg = $('.msg', successDialog), dlgButtons = {};
			msg.text(text);
			successDialog.css('display', 'block');
			dlgButtons[designerStrRes.quitBtn] = function() {
				successDialog.css('display', 'none');
				successDialog.dialog('destroy');
				fnOnExit();
			};
			dlgButtons[designerStrRes.saveBtn] = function() {
				successDialog.css('display', 'none');
				successDialog.dialog('destroy');
				fnOnSave();
			};
			successDialog.dialog({
				autoOpen: true,
				closeOnEscape: true,
				bgiframe: true,
				modal: true,
				resizable: false,
				title: dlgTitle,
				buttons: dlgButtons
			});
		}

		function populateDataToSave(cssConf, data) {
			var dataIdx = 0;
			for (var selectorText in cssConf){
				var cssProperties = cssConf[selectorText];
				var proplist = [];
				for (var cssPropertyName in cssProperties){
					var property = cssProperties[cssPropertyName];
					if (property && property.isDirty && property.isDirty()){
						proplist.push(cssPropertyName + ':' + property.toString());
					}
				}
				if (proplist.length > 0){
					//if (window.console) console.log(selectorText, '{',proplist.join(';') + ';', '}');
					dataIdx++;
					data['slctr'+dataIdx] = selectorText;
					data['cntnt'+dataIdx] = proplist.join(';') + ';';
				}
			}
			data['selectorCount'] = dataIdx;
			return dataIdx;
		}
		function displayDialog(src, dlgTitle, text){
			var msg = $('.msg', src);
			msg.text(text);
			src.css('display', 'block');
			src.dialog({
				autoOpen: true,
				closeOnEscape: true,
				bgiframe: true,
				modal: true,
				resizable: false,
				title:''+dlgTitle,
				buttons: {
					"Ok": function() {
						src.css('display', 'none');
						src.dialog('destroy');
					}
				}
			});
		}
		function save(data, conf, displayDlg) {
			var cssConf = conf.srcCssConf;
			data['account'] = conf.account;
			data['design'] = conf.design;
			$.ajax({
				async:false,
				type: 'POST',
				url: 'CSSDesignFactory.asp',
				data: data,
				cache: false,
				global: false,
				dataType:'xml',
				success: function(xml){
					var result = $('result', xml);
					var message = $('translatedtext', result);
					if (result.attr('type') == 'error'){
						displayDialog(errDialog, designerStrRes.errorDlgTitle, message.text());
					} else {
						for (var selectorText in cssConf){
							var cssProperties = cssConf[selectorText];
							for (var cssPropertyName in cssProperties){
								var property = cssProperties[cssPropertyName];
								if (property && property.isDirty && property.isDirty()){
									property.setDirty(false);
								}
							}
						}
						if (displayDlg) displayDialog(successDialog, designerStrRes.successDlgTitle, message.text());
					}
				},
				error:function(XMLHttpRequest, textStatus, errorThrown) {
					alert(XMLHttpRequest.responseText);
				}
			});
		}

		keepSessionAlive();
		buttons.push({
			id: 'saveBtn',
			type: 'action',
			title: designerStrRes.saveBtn,
			action: function(btn, conf) {
				var data = {}, dataIdx = 0, cssConf;
				if (conf.account && conf.design) {
					cssConf = conf.srcCssConf;
					dataIdx = populateDataToSave(cssConf, data);
					if (dataIdx == 0) {
						displayDialog(errDialog, designerStrRes.errorDlgTitle, designerStrRes.noDirtyProperty);
					} else {
						save(data, conf, true);
					}
				}
			}
		});
		buttons.push({
			id:'cancelBtn',
			type:'action',
			title:designerStrRes.quitBtn,
			action: function(btn, conf){
				var data = {}, cssConf = conf.srcCssConf;
				var dataIdx = populateDataToSave(cssConf, data);
				if (conf.src) {
					if (dataIdx > 0) {
						exitFromSmartSkins(designerStrRes.quitBtn, designerStrRes.confirmCancel, function() { save(data, conf, false); document.location = conf.src; }, function() { document.location = conf.src });
					} else {
						document.location = conf.src;
					}
				}
			}
		});
	}
	buttons.push({
		id:'resetBtn',
		type:'action',
		title:designerStrRes.resetBtn,
		action:function(btn, conf){
			askForConfirm(designerStrRes.resetBtn, designerStrRes.confirmReset, function(){
				conf.propertyModel.reset();
				conf.uiModel.reset();
			});
		}
	});
	cssDesignerConf.toolbar.addGroup({
		title:designerStrRes.controlBtnGroup,
		buttons:buttons
	});

	try{
		initCSSDesigner(cssDesignerConf);
	} catch(e){
		alert('unexpected exception:' + e.name + '. Error message:' + e.message + '.');
	}
	cssDesignerConf.renderToolbar();
	cssDesignerConf.formatCSSConf();
	registerIFrameListener();
	initDone = true;

	var wnd=$(window), toolbar=$('.toolbar'), resizeTimer = null;
	webSitePreview=$('#WebSitePreview');
	function resize(){
		var windowHeight = wnd.height();
		var toolbarHeight = toolbar.outerHeight();
		var height=windowHeight-toolbarHeight + 'px';
		webSitePreview.css('height', height);
		//if (window.console) console.log(windowHeight, toolbarHeight, '=>', height, toolbar.length);
	}
	wnd.bind('resize', function() {
		if (resizeTimer) clearTimeout(resizeTimer);
		resizeTimer = setTimeout(resize, 100);
	});
	resize();

	webSitePreviewOverlay = $('<div id="overlay"></div>');
	webSitePreviewOverlay.appendTo('body');

});

