var version='Build version: 5.14.0.20080814-113443';
function CatalogCategoryController(id){
this.id=id;}
CatalogCategoryController.prototype.id="CatalogCategoryController";CatalogCategoryController.prototype.rootCategoryId="";CatalogCategoryController.prototype.categoryTreeArray=undefined;CatalogCategoryController.prototype.categoryMap=undefined;
CatalogCategoryController.prototype.init=function(){
Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);
resource.applyProperties(this.id+"Properties",this);
if(this.categoryTreeArray==undefined){this.load();
}else{this.setData(this.categoryTreeArray);}}
CatalogCategoryController.prototype.setData=function(dataArray){
if(dataArray!=undefined){
var isInitializing=(this.categoryTreeArray==undefined);
this.categoryTreeArray=dataArray["CATEGORIES"];this.categoryMap=this.getCategoryMap(this.categoryTreeArray);
if(isInitializing){Workspace.events.throwEvent(Workspace.events.EVENT_CONTROLLER_INITIALIZED,this);}
Workspace.events.throwEvent(Workspace.events.EVENT_CATEGORY_TREE_UPDATED,this);}}
CatalogCategoryController.prototype.getCategoryMap=function(categoryTree,categoryParentId){
var categoryMap=new Array();var map=new Array();
if(categoryTree!=undefined){
for(var index in categoryTree){
map=categoryTree[index];
if(categoryParentId!=undefined){map["PARENT_CATEGORY_ID"]=categoryParentId;}
categoryMap[categoryTree[index]["CATEGORY_ID"]]=categoryTree[index];
if(categoryTree[index]["CATEGORIES"]!=undefined&&categoryTree[index]["CATEGORIES"].length>0){
categoryMap=MapUtils.putAll(categoryMap,this.getCategoryMap(categoryTree[index]["CATEGORIES"],categoryTree[index]["CATEGORY_ID"]));}}}
return categoryMap;}
CatalogCategoryController.prototype.load=function(){
var params=new Array();
if(this.rootCategoryId!=""){params[params.length]=["rootCategoryId",this.rootCategoryId];}
this.sendRequest("getCatalogTree",params);}
CatalogCategoryController.prototype.sendRequest=function(pActionType,pParams){
det.sendRequest({serverUrl:Workspace.serverContext+"/action/"+pActionType,action:pActionType,parameters:pParams,callingController:this});}
CatalogCategoryController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED&&attributes.callingController==this){if(attributes!=undefined&&attributes.response!=undefined&&attributes.response["catalogTree"]!=undefined){this.setData(attributes.response["catalogTree"]);}}}
function CatalogController(id){
this.id=id;return this;}
CatalogController.prototype.id="CatalogController";CatalogController.prototype.elementId="";CatalogController.prototype.categoryElementId="";CatalogController.prototype.categoryTreeArray=undefined;CatalogController.prototype.catalogArray=undefined;CatalogController.prototype.categoryTotalItemCount=undefined;CatalogController.prototype.generatedItemsArray=undefined;CatalogController.prototype.handlerUrl="";CatalogController.prototype.draggedItem=undefined;CatalogController.prototype.callout=undefined;CatalogController.prototype.displayedCategoryId="";CatalogController.prototype.highlightedItemId="";CatalogController.prototype.itemToHighlight="";CatalogController.prototype.categoryToOpenAtStartup="";CatalogController.prototype.swatchUrl="";CatalogController.prototype.thumbnailPrefix="";CatalogController.prototype.thumbnailSuffix="";CatalogController.prototype.isInitialized=false;CatalogController.prototype.isGenerated=false;CatalogController.prototype.isDisplayItems=true;CatalogController.prototype.isDisplayOutfits=true;CatalogController.prototype.isOpenDefaultCategoryAtStartup=false;CatalogController.prototype.itemsColumns=undefined;CatalogController.prototype.itemsRows=undefined;CatalogController.prototype.isRemoveIncompatibleItems=false;CatalogController.prototype.pageIndex=0;CatalogController.prototype.pageCount=0;
CatalogController.prototype.init=function(){
this.categoryTreeArray=new Array();this.catalogArray=new Array();this.categoryTotalItemCount=new Array();this.generatedItemsArray=new Array();
this.handlerUrl=Workspace.serverContext+"/action/catalog";
resource.applyProperties(this.id+"Properties",this);
if(Workspace.query.category!=undefined){this.categoryToOpenAtStartup=Workspace.query.category;}
Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);
this.isInitialized=true;}
CatalogController.prototype.show=function(){
if(!this.isGenerated){
this.isGenerated=true;Workspace.events.addListener(Workspace.events.EVENT_BODYSET_CHANGED,this);Workspace.events.addListener(Workspace.events.EVENT_CATEGORY_TREE_UPDATED,this);
loopUntil("CatalogCategory.categoryTreeArray!=undefined",this.id+".loadCategoryTree()");}
if(this.categoryToOpenAtStartup!=""){this.loadCategory(this.categoryToOpenAtStartup);this.categoryToOpenAtStartup="";}}
CatalogController.prototype.setData=function(dataArray){
if(dataArray!=undefined){
var catID=dataArray["catID"];
if(catID!=undefined){
if(dataArray["selectedItem"]!=undefined&&catID!=undefined){}
if(dataArray["itemIds"]!=undefined&&this.isDisplayItems){this.catalogArray[catID]=MapUtils.getClone(dataArray["itemIds"]);
Items.loadItemInfo(
this.catalogArray[catID],this.id+".filterItems('"+catID+"')");}
if(this.categoryTotalItemCount[catID]==undefined&&this.catalogArray[catID]!=undefined){this.categoryTotalItemCount[catID]=this.catalogArray[catID].length;}}}}
CatalogController.prototype.filterItems=function(categoryId){
var tmpCatalogArray=new Array();
for(var itemIndex in this.catalogArray[categoryId]){
itemId=this.catalogArray[categoryId][itemIndex];
if(!Items.isFallback(itemId)&&Items.isAvailable(itemId)&&(!this.isRemoveIncompatibleItems||(this.isRemoveIncompatibleItems&&Items.isCompatible(itemId)))){
tmpCatalogArray.push(this.catalogArray[categoryId][itemIndex]);}}
this.catalogArray[categoryId]=tmpCatalogArray;
this.displayCategory(categoryId);}
CatalogController.prototype.loadCategoryTree=function(){
this.categoryTreeArray=new Array();
if(typeof(CatalogCategory)!="undefined"){this.categoryTreeArray=CatalogCategory.categoryTreeArray;}else{this.categoryTreeArray=new Array();}
this.generateCategoryTree();this.calculateEstimatedNumberOfDisplayedItems();
var isCategoryToOpenAtStartupFound=false;
if(this.isOpenDefaultCategoryAtStartup){
for(var i=0;i<this.categoryTreeArray.length;i++){
if(this.categoryToOpenAtStartup==this.categoryTreeArray[i]["CATEGORY_ID"]||isCategoryToOpenAtStartupFound){isCategoryToOpenAtStartupFound=true;break;
}else if(this.categoryTreeArray[i]["CATEGORIES"]!=undefined&&this.categoryTreeArray[i]["CATEGORIES"].length>0){
for(var j=0;j<this.categoryTreeArray[i]["CATEGORIES"].length;j++){
if(this.categoryToOpenAtStartup==this.categoryTreeArray[i]["CATEGORIES"][j]["CATEGORY_ID"]){isCategoryToOpenAtStartupFound=true;break;}}}}
if(!isCategoryToOpenAtStartupFound){
if(this.categoryTreeArray[0]!=undefined&&this.categoryTreeArray[0]["CATEGORIES"]!=undefined&&this.categoryTreeArray[0]["CATEGORIES"][0]!=undefined){this.categoryToOpenAtStartup=this.categoryTreeArray[0]["CATEGORIES"][0]["CATEGORY_ID"];
}else if(this.categoryTreeArray[0]!=undefined){this.categoryToOpenAtStartup=this.categoryTreeArray[0]["CATEGORY_ID"];}}}}
CatalogController.prototype.generateCategoryTree=function(){}
CatalogController.prototype.loadCategory=function(categoryId){
if(this.isGenerated){
categoryId=(categoryId!=undefined?categoryId : this.displayedCategoryId);
if(categoryId!=""&&categoryId!=undefined){
this.resetItemHighlight();
if(categoryId==undefined||categoryId==""){
if(this.displayedCategoryId!=undefined&&this.displayedCategoryId!=""){categoryId=this.displayedCategoryId;}else if(this.categoryTreeArray[0]!=undefined){
if(this.categoryTreeArray[0]["CATEGORIES"]!=undefined&&this.categoryTreeArray[0]["CATEGORIES"][0]!=undefined&&this.categoryTreeArray[0]["CATEGORIES"][0]["CATEGORY_ID"]!=undefined){categoryId=this.categoryTreeArray[0]["CATEGORIES"][0]["CATEGORY_ID"];}else{categoryId=this.categoryTreeArray[0]["CATEGORY_ID"];}}}
for(var i=0;i<this.categoryTreeArray.length;i++){
if(this.categoryTreeArray[i]["CATEGORY_ID"]==categoryId&&this.categoryTreeArray[i]["CATEGORIES"]!=undefined&&this.categoryTreeArray[i]["CATEGORIES"].length>0){
categoryId=this.categoryTreeArray[i]["CATEGORIES"][0]["CATEGORY_ID"];break;}}
var parameters=new Array();parameters[parameters.length]=["catID",categoryId];
if(typeof(CatalogFilter)!="undefined"){parameters[parameters.length]=["filters",CatalogFilter.serialize(categoryId)];}
this.displayedCategoryId=categoryId;
this.sendRequest("getCollection",parameters);}else{log.error("loadCategory: Category ID is not defined",this);}}}
CatalogController.prototype.displayCategory=function(categoryId){
this.pageCount=Math.ceil(this.catalogArray[categoryId].length /(this.itemsColumns * this.itemsRows));this.pageIndex=0;}
CatalogController.prototype.findItem=function(itemId,stepState){
stepState=(stepState==undefined?0 : stepState);
switch(stepState){
case 0:
var item=Items.getItemFromItemId(itemId);
if(item==undefined){Items.loadItemInfo([itemId],this.id+".findItem("+itemId+",1)");}else{this.findItem(itemId,1);}
break;
case 1:
var item=Items.getItemFromItemId(itemId);
if(item==undefined){log.error("findItem: Item could not be found",this);}else if(item["CATEGORIES"]!=undefined&&item["CATEGORIES"][0]!=undefined){
if(item["CATEGORIES"][0]["CATEGORY_ID"]!=this.displayedCategoryId){this.loadCategory(item["CATEGORIES"][0]["CATEGORY_ID"]);Workspace.events.addEventScript(Workspace.events.EVENT_CATALOG_CATEGORY_CHANGED,this.id+".findItem("+itemId+",2)",true);
}else{this.findItem(itemId,2);}}
break;
case 2:
this.highlightItem(itemId);break;}}
CatalogController.prototype.generateItems=function(pStartIndex,pEndIndex,categoryId,containerElementId){
ParserUtils.preloadTemplate(this.id+"ItemTemplate",this.id+"._generateItems("+pStartIndex+","+pEndIndex+","+categoryId+",'"+containerElementId+"')");}
CatalogController.prototype.generateItemPlaceholders=function(){
var content="";var containerElement=document.getElementById(this.id+"ItemsContainer");
for(var i=0;i<this.catalogArray[this.displayedCategoryId].length;i++){
content+="<div id='"+this.id+"Item_"+this.catalogArray[this.displayedCategoryId][i]+"' "+
"style='position:absolute;"+
"left:"+parseInt(containerElement.getAttribute("itemWidth"))*(i%this.itemsColumns)+"px;"+
"top:"+parseInt(containerElement.getAttribute("itemHeight"))* Math.floor((i/this.itemsColumns))+"px;'>"+
"</div>";}
if(this.catalogArray[this.displayedCategoryId].length>0){
content+="<img src='/images/spacer.gif' style='left:0px;top:"+(parseInt(this.catalogArray[this.displayedCategoryId].length / this.itemsColumns)+(document.getElementById(this.id+"Nav")!=undefined?2 : 0))* containerElement.getAttribute("itemHeight")+"px;width:1px;height:1px;'/>";}else{
content+=resource.get("Vdr.Category.Empty");}
containerElement.innerHTML=content;}
CatalogController.prototype._generateItems=function(pStartIndex,pEndIndex,categoryId,containerElementId){
var containerElement=document.getElementById(containerElementId);var itemsArray=this.generatedItemsArray[categoryId];var content="";
for(var i=pStartIndex;i<pEndIndex;i++){if(itemsArray[i]==undefined){
if(this.catalogArray[categoryId][i]!=undefined){
if(Items.isAvailable(this.catalogArray[categoryId][i])){
document.getElementById(this.id+"Item_"+this.catalogArray[categoryId][i]).innerHTML=this.getItemHTML(this.catalogArray[categoryId][i],i);}}
itemsArray[i]=true;}}
if(content.length>0){containerElement.innerHTML+=content;}}
CatalogController.prototype.scrollTo=function(pTop){
var containerElement=document.getElementById(this.id+"ItemsContainer");
if(this.catalogArray[this.displayedCategoryId]!=undefined){
this.pageIndex=Math.floor(pTop /(this.itemsRows * parseInt(containerElement.getAttribute("itemHeight"))));ParserUtils.applyTemplate(this.id+"NavTemplate",this.id+"Nav");
Workspace.message.hide(this.callout);
var startView=pTop;var endView=startView+parseInt(containerElement.style.height);
var startIndex=Math.floor(startView /(parseInt(containerElement.getAttribute("itemHeight"))/this.itemsColumns))-this.itemsColumns;
var endIndex=startIndex+(this.itemsColumns*(this.itemsRows*2));
if(startIndex<0){startIndex=0;}
if(endIndex>this.catalogArray[this.displayedCategoryId].length){endIndex=this.catalogArray[this.displayedCategoryId].length;}
if(containerElement.scrollTop!=startView){containerElement.scrollTop=startView;}
this.generateItems(startIndex,endIndex,this.displayedCategoryId,this.id+"ItemsContainer");}}
CatalogController.prototype.startAnimateItemDrag=function(pElement){
var dragElement=document.getElementById("catalogAnimatedThumbnail");
if(dragElement!=undefined){
dragElement.src=pElement.src;dragElement.style.display="block";
dragElement.style.left=getAbsLeft(pElement)+"px";dragElement.style.top=getAbsTop(pElement)+"px";dragElement.style.width=getWidth(pElement)+"px";dragElement.style.height=getHeight(pElement)+"px";
var targetX=getAbsLeft(document.getElementById(Model.imageElementId))+parseInt(resource.get("ModelProperties/imageWidth")-parseInt(dragElement.style.width))/2;
var targetY=getAbsTop(document.getElementById(Model.imageElementId))+parseInt(resource.get("ModelProperties/imageHeight")-parseInt(dragElement.style.height))/2;
var attributes=new Array();attributes["tLeft"]=targetX;attributes["tTop"]=targetY;attributes["onComplete"]="Anim.hide('catalogAnimatedThumbnail')";
Anim.animateElement(dragElement.id,attributes);}}
CatalogController.prototype.resetAllCategoriesExcept=function(categoryId){
for(var i=0;i<this.categoryTreeArray.length;i++){if(this.categoryTreeArray[i]["CATEGORY_ID"]!=categoryId){Anim.reset("catalogCategory_"+this.categoryTreeArray[i]["CATEGORY_ID"],"sectionCatalogDiv");document.getElementById(this.id+"ItemsContainer").innerHTML="";}}}
CatalogController.prototype.sendRequest=function(pActionType,pParams){
var requestParams=new Array();
requestParams[requestParams.length]=["getDataOnly","true"];
if(pParams!=undefined){requestParams=requestParams.concat(pParams);}
det.sendRequest({serverUrl:Workspace.serverContext+"/action/"+pActionType,action:pActionType,parameters:requestParams,callingController:this,group:"Catalog"});}
CatalogController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED&&attributes.callingController==this){if(attributes!=undefined&&attributes.response!=undefined){this.setData(attributes.response);}}else if(eventKey==Workspace.events.EVENT_BODYSET_CHANGED){
this.loadCategory();}else if(eventKey==Workspace.events.EVENT_CATEGORY_TREE_UPDATED){this.loadCategoryTree();}}
CatalogController.prototype.getItemHTML=function(itemId,index){
var containerElement=document.getElementById(this.id+"ItemsContainer");
var attributes=new Array();
var item=Items.getItemFromItemId(itemId);
if(item!=undefined){
attributes["controllerId"]=this.id;attributes["index"]=index;
attributes=MapUtils.putAll(attributes,item);
return ParserUtils.parseTemplate(this.id+"ItemTemplate",attributes);}}
CatalogController.prototype.scrollToItem=function(itemId){
var containerElement=document.getElementById(this.id+"ItemsContainer");
var itemIndex=this.getItemIndex(itemId);
if(itemIndex!=undefined){
var row=Math.floor(itemIndex / this.itemsColumns);
if(row % this.itemsRows==this.itemsRows-1){row-=1;}
var topPosition=row * parseInt(containerElement.getAttribute("itemHeight"));
if(itemIndex<this.itemsColumns){
topPosition=0;}
this.scrollTo(topPosition);}}
CatalogController.prototype.getItemIndex=function(itemId){
var itemIndex=0;var itemCount=0;
for(var index in this.catalogArray[this.displayedCategoryId]){
if(this.catalogArray[this.displayedCategoryId][index]==itemId){itemIndex=itemCount;break;}
if(Items.isAvailable(this.catalogArray[this.displayedCategoryId][index])){itemCount++;}}
return itemIndex;}
CatalogController.prototype.highlightItem=function(itemId){
this.scrollToItem(itemId);
var element=document.getElementById(this.id+"ItemImage_"+itemId);if(element!=undefined){element.className=element.getAttribute("highlightClass");}
this.highlightedItemId=itemId;}
CatalogController.prototype.resetItemHighlight=function(){
if(this.highlightedItemId!=""){var element=document.getElementById(this.id+"ItemImage_"+this.highlightedItemId);
if(element!=undefined){element.className=element.getAttribute("defaultClass");}}
this.highlightedItemId="";}
CatalogController.prototype.calculateEstimatedNumberOfDisplayedItems=function(){
var itemWidth=parseInt(document.getElementById(this.id+"ItemsContainer").getAttribute("itemWidth"));var itemHeight=parseInt(document.getElementById(this.id+"ItemsContainer").getAttribute("itemHeight"));var containerWidth=parseInt(document.getElementById(this.id+"ItemsContainer").style.width);var containerHeight=parseInt(document.getElementById(this.id+"ItemsContainer").style.height);
this.itemsColumns=Math.floor(containerWidth/itemWidth);
if(this.itemsRows==undefined){this.itemsRows=Math.ceil(containerHeight/itemHeight);}}
CatalogController.prototype.getParentCategoryId=function(categoryId){
var value=categoryId;
for(var i=0;i<this.categoryTreeArray.length;i++){
if(this.categoryTreeArray[i]["CATEGORIES"]!=undefined){
for(var j=0;j<this.categoryTreeArray[i]["CATEGORIES"].length;j++){if(this.categoryTreeArray[i]["CATEGORIES"][j]["CATEGORY_ID"]==categoryId){value=this.categoryTreeArray[i]["CATEGORY_ID"];break;}}}}
return value;}
CatalogController.prototype.showPage=function(index){
if(index<0){index=0;}else if(index>this.pageCount-1){index=this.pageCount-1;}
this.scrollTo((index * this.itemsRows)* parseInt(document.getElementById(this.id+"ItemsContainer").getAttribute("itemHeight")));
ParserUtils.applyTemplate(this.id+"NavTemplate",this.id+"Nav");}
function CatalogDropdownController(id){jsClass.extend(this,[CatalogController]);
this.id=id;return this;}
CatalogDropdownController.prototype.categoryItemHeight=20;CatalogDropdownController.prototype.templateId="CategoryCurrentTemplate";
CatalogDropdownController.prototype.generateCategoryTree=function(){
ParserUtils.preloadTemplate(this.id+"CategoryTemplate",this.id+".generateCategoryTreeWithHtml()");}
CatalogDropdownController.prototype.generateCategoryTreeWithHtml=function(){
var containerElement=document.getElementById(this.categoryElementId);var categoryContainerHTML="";var categoryTemplateHTML=ParserUtils.getTemplateHtml(this.id+"CategoryTemplate");var attributes=undefined;var rowCount=0;
var parentCategoryOfDisplayedCategory=this.getParentCategoryId(this.displayedCategoryId);
if(containerElement!=undefined){
for(var i=0;i<this.categoryTreeArray.length;i++){
if(this.categoryTreeArray[i]["CATEGORY_ID"]!=parentCategoryOfDisplayedCategory){
attributes=new Array();attributes["controllerId"]=this.id;attributes["categoryId"]=this.categoryTreeArray[i]["CATEGORY_ID"];attributes["categoryLevel"]=0;attributes["isDisplayItems"]=this.isDisplayItems;attributes["isDisplayOutfits"]=this.isDisplayOutfits;attributes["categoryName"]=this.categoryTreeArray[i]["CATEGORY_DESC"];
categoryContainerHTML+=ParserUtils.parseHtml(categoryTemplateHTML,attributes);rowCount++;}}
containerElement.setAttribute("tHeight",""+(rowCount * parseInt(containerElement.getAttribute("categoryHeight"))));}
ParserUtils.setContainerHtml(this.categoryElementId,categoryContainerHTML);
this.generateSubCategoryDropdown(this.displayedCategoryId);}
CatalogDropdownController.prototype._getParentCategoryIndex=function(parentCategoryId){var parentCategoryIndex=undefined;
for(var i=0;i<this.categoryTreeArray.length;i++){if(this.categoryTreeArray[i]["CATEGORIES"]!=undefined){for(var j=0;j<this.categoryTreeArray[i]["CATEGORIES"].length;j++){if(this.categoryTreeArray[i]["CATEGORIES"][j]["CATEGORY_ID"]==parentCategoryId||
this.categoryTreeArray[i]["CATEGORY_ID"]==parentCategoryId){parentCategoryIndex=i;break;}}}}
return parentCategoryIndex;}
CatalogDropdownController.prototype.getSubCategoryIdListByIndex=function(parentCategoryIndex){
var subCategoryIdList=new Array();
if(parentCategoryIndex!=undefined&&this.categoryTreeArray[parentCategoryIndex]["CATEGORIES"]!=undefined){for(var i=0;i<this.categoryTreeArray[parentCategoryIndex]["CATEGORIES"].length;i++){subCategoryIdList[subCategoryIdList.length]=this.categoryTreeArray[parentCategoryIndex]["CATEGORIES"][i]["CATEGORY_ID"];}}
return subCategoryIdList;}
CatalogDropdownController.prototype.getSubCategoryIdListById=function(parentCategoryId){
var parentCategoryIndex=this._getParentCategoryIndex(parentCategoryId);
return this.getSubCategoryIdListByIndex(parentCategoryIndex);}
CatalogDropdownController.prototype.generateSubCategoryDropdown=function(categoryId){
var containerHTML="";var categoryArrayIndex=undefined;var categoryTemplateHTML=ParserUtils.getTemplateHtml(this.id+"CategoryTemplate");var attributes=undefined;var rowCount=0;
categoryArrayIndex=this._getParentCategoryIndex(categoryId);
if(categoryArrayIndex!=undefined&&this.categoryTreeArray[categoryArrayIndex]["CATEGORIES"]!=undefined){
var parentCategoryOfDisplayedCategoryId=this.getParentCategoryId(this.displayedCategoryId);
for(var i=0;i<this.categoryTreeArray[categoryArrayIndex]["CATEGORIES"].length;i++){if(this.categoryTreeArray[categoryArrayIndex]["CATEGORIES"][i]["CATEGORY_ID"]!=this.displayedCategoryId){attributes=new Array();attributes["controllerId"]=this.id;attributes["categoryLevel"]=1;attributes["categoryId"]=this.categoryTreeArray[categoryArrayIndex]["CATEGORIES"][i]["CATEGORY_ID"];attributes["categoryName"]=this.categoryTreeArray[categoryArrayIndex]["CATEGORIES"][i]["CATEGORY_DESC"];
containerHTML+=ParserUtils.parseHtml(categoryTemplateHTML,attributes);rowCount++;}}
document.getElementById(this.id+"SubCategories").setAttribute("tHeight",""+(rowCount * parseInt(document.getElementById(this.id+"SubCategories").getAttribute("categoryHeight"))));}
ParserUtils.setContainerHtml(this.id+"SubCategories",containerHTML);}
CatalogDropdownController.prototype.displayCategory=function(categoryId){
this.super_CatalogController_displayCategory(categoryId);
this.displayedCategoryId=categoryId;this.generatedItemsArray[categoryId]=new Array();
var catalogArray=this.catalogArray[categoryId];
if(catalogArray!=undefined){
var attributes=new Array();attributes["controllerId"]=this.id;attributes["catalogElementId"]=this.catalogElementId;attributes["subCategoryId"]="";attributes["count"]=catalogArray.length;
var isFound=false;var categoryArrayIndex=undefined;
for(var i=0;i<this.categoryTreeArray.length;i++){
if(!isFound&&this.categoryTreeArray[i]["CATEGORIES"]!=undefined){for(var j=0;j<this.categoryTreeArray[i]["CATEGORIES"].length;j++){if(this.categoryTreeArray[i]["CATEGORIES"][j]["CATEGORY_ID"]==categoryId){
attributes["catalogCategoryLabel"]=this.categoryTreeArray[i]["CATEGORY_DESC"];attributes["catalogSubCategoryLabel"]=this.categoryTreeArray[i]["CATEGORIES"][j]["CATEGORY_DESC"];attributes["categoryId"]=this.categoryTreeArray[i]["CATEGORY_ID"];attributes["subCategoryId"]=this.categoryTreeArray[i]["CATEGORIES"][j]["CATEGORY_ID"];attributes["total"]=parseInt(this.isDisplayItems&&!isNaN(this.categoryTreeArray[i]["CATEGORIES"][j]["NUMBER_OF_ITEMS"])?this.categoryTreeArray[i]["CATEGORIES"][j]["NUMBER_OF_ITEMS"] : 0)+parseInt(this.isDisplayOutfits&&!isNaN(this.categoryTreeArray[i]["CATEGORIES"][j]["NUMBER_OF_OUTFITS"])?this.categoryTreeArray[i]["CATEGORIES"][j]["NUMBER_OF_OUTFITS"] : 0);
isFound=true;categoryArrayIndex=i;break;}}}
if(!isFound&&this.categoryTreeArray[i]["CATEGORY_ID"]==categoryId){
attributes["categoryId"]=categoryId;attributes["subCategoryId"]="";attributes["catalogCategoryLabel"]=this.categoryTreeArray[i]["CATEGORY_DESC"];attributes["catalogSubCategoryLabel"]="";attributes["total"]=(this.isDisplayItems&&!isNaN(parseInt(this.categoryTreeArray[i]["NUMBER_OF_ITEMS"]))?parseInt(this.categoryTreeArray[i]["NUMBER_OF_ITEMS"]): 0)+(this.isDisplayOutfits&&!isNaN(parseInt(this.categoryTreeArray[i]["NUMBER_OF_OUTFITS"]))?parseInt(this.categoryTreeArray[i]["NUMBER_OF_OUTFITS"]): 0);
isFound=true;break;}}
ParserUtils.applyTemplate(this.id+this.templateId,this.id+"CategoryCurrent",attributes);ParserUtils.applyTemplate(this.id+"NavTemplate",this.id+"Nav");
var containerElement=document.getElementById(this.id+"ItemsContainer");
this.generateItemPlaceholders();this.generateItems(0,(this.itemsColumns*(this.itemsRows*2)),categoryId,this.id+"ItemsContainer");containerElement.scrollTop=0;
if(this.itemToHighlight!=""){this.highlightItem(this.itemToHighlight);this.itemToHighlight="";}
if(typeof(CatalogFilter)!="undefined"){CatalogFilter.generate(categoryId);}
this.generateCategoryTree();
Workspace.events.throwEvent(Workspace.events.EVENT_CATALOG_CATEGORY_CHANGED,this);}else{log.debug("Category "+categoryId+" is empty",this);}}
function CatalogStickController(id){jsClass.extend(this,[CatalogController]);
this.id=id;return this;}
CatalogStickController.prototype.generateCategoryTree=function(){
ParserUtils.applyTemplate(this.id+"CategoryStickTemplate",this.categoryElementId,new Array());}
CatalogStickController.prototype.displayCategory=function(categoryId){
this.super_CatalogController_displayCategory(categoryId);
this.displayedCategoryId=categoryId;this.generatedItemsArray[categoryId]=new Array();
var catalogArray=this.catalogArray[ categoryId ];var containerElement=document.getElementById(this.id+"ItemsContainer_"+categoryId);var requestedCategoryId="";var requestedSubCategoryId="";
if(catalogArray!=undefined&&containerElement!=undefined){
var itemHeight=parseInt(containerElement.getAttribute("itemHeight"));
ParserUtils.setContainerHtml(this.id+"ItemsContainer_"+categoryId,"<img src='/images/spacer.gif' style='left:0px;top:"+parseInt(catalogArray.length / this.itemsColumns*itemHeight)+"px;width:1px;height:1px;'></div>");containerElement.scrollTop=0;
var itemCountElement=document.getElementById(this.id+"ItemsCount_"+categoryId);
if(itemCountElement!=undefined){
var attributes=new Array();attributes["categoryId"]=categoryId;attributes["count"]=this.catalogArray[categoryId].length;
for(var categoryIndex in this.categoryTreeArray){if(this.categoryTreeArray[categoryIndex]["CATEGORY_ID"]==categoryId){
requestedCategoryId=categoryId;attributes["total"]=(this.isDisplayItems&&!isNaN(parseInt(this.categoryTreeArray[categoryIndex]["NUMBER_OF_ITEMS"]))?parseInt(this.categoryTreeArray[categoryIndex]["NUMBER_OF_ITEMS"]): 0)+(this.isDisplayOutfits&&!isNaN(parseInt(this.categoryTreeArray[categoryIndex]["NUMBER_OF_OUTFITS"]))?parseInt(this.categoryTreeArray[categoryIndex]["NUMBER_OF_OUTFITS"]): 0);break;}
for(var subCatIndex in this.categoryTreeArray[categoryIndex]["CATEGORIES"]){if(this.categoryTreeArray[categoryIndex]["CATEGORIES"][subCatIndex]["CATEGORY_ID"]==categoryId){
requestedCategoryId=this.categoryTreeArray[categoryIndex]["CATEGORY_ID"];requestedSubCategoryId=categoryId;attributes["total"]=parseInt(this.isDisplayItems&&!isNaN(this.categoryTreeArray[categoryIndex]["CATEGORIES"][subCatIndex]["NUMBER_OF_ITEMS"])?this.categoryTreeArray[categoryIndex]["CATEGORIES"][subCatIndex]["NUMBER_OF_ITEMS"] : 0)+parseInt(this.isDisplayOutfits&&!isNaN(this.categoryTreeArray[categoryIndex]["CATEGORIES"][subCatIndex]["NUMBER_OF_OUTFITS"])?this.categoryTreeArray[categoryIndex]["CATEGORIES"][subCatIndex]["NUMBER_OF_OUTFITS"] : 0);break;break;}}}
ParserUtils.setContainerHtml(this.id+"ItemsCount_"+categoryId,ParserUtils.parseHtml(itemCountElement.getAttribute("label"),attributes));}
ParserUtils.applyTemplate(this.id+"NavTemplate",this.id+"Nav");
this.generateItemPlaceholders();this.generateItems(0,(this.itemsColumns*(this.itemsRows*2)),categoryId,this.id+"ItemsContainer_"+categoryId);
if(typeof(CatalogFilter)!="undefined"){CatalogFilter.generate(categoryId);}
if(this.itemToHighlight!=""){this.highlightItem(this.itemToHighlight);this.itemToHighlight="";}
if(requestedSubCategoryId==categoryId){Anim.openSingle(this.id+"Category_"+requestedCategoryId);Anim.openSingle(this.id+"Category_"+requestedSubCategoryId);}else{Anim.openSingle(this.id+"Category_"+categoryId);}
Workspace.events.throwEvent(Workspace.events.EVENT_CATALOG_CATEGORY_CHANGED,this);}}
CatalogStickController.prototype.calculateEstimatedNumberOfDisplayedItems=function(){
var itemWidth=parseInt(document.getElementById(this.id+"ItemsContainer").getAttribute("itemWidth"));var itemHeight=parseInt(document.getElementById(this.id+"ItemsContainer").getAttribute("itemHeight"));var containerWidth=parseInt(document.getElementById(this.categoryElementId).style.width);var containerHeight=parseInt(document.getElementById(this.categoryElementId).style.height);
this.itemsColumns=Math.floor(containerWidth/itemWidth);this.itemsRows=Math.ceil(containerHeight/itemHeight);}
CatalogStickController.prototype.scrollTo=function(pTop){
var containerElement=document.getElementById(this.id+"ItemsContainer_"+this.displayedCategoryId);
var startView=pTop;var endView=startView+parseInt(containerElement.style.height);
var startIndex=Math.floor(startView /(parseInt(containerElement.getAttribute("itemHeight"))/this.itemsColumns))-this.itemsColumns;
var endIndex=startIndex+(this.itemsColumns*(this.itemsRows*2));
if(startIndex<0){startIndex=0;}
if(endIndex>this.catalogArray[this.displayedCategoryId].length){endIndex=this.catalogArray[this.displayedCategoryId].length;}
if(containerElement.scrollTop!=startView){containerElement.scrollTop=startView;}
this.generateItems(startIndex,endIndex,this.displayedCategoryId,this.id+"ItemsContainer_"+this.displayedCategoryId);}
CatalogStickController.prototype.resetAllCategoriesExcept=function(categoryId){
for(var i=0;i<this.categoryTreeArray.length;i++){if(this.categoryTreeArray[i][0]!=categoryId){Anim.reset(this.id+"Category_"+this.categoryTreeArray[i][0],"sectionCatalogDiv");document.getElementById(this.id+"ItemsContainer_"+this.categoryTreeArray[i][0]).innerHTML="";}}}
function FilterController(pId){
this.id=pId;this.handlerUrl=Workspace.serverContext+"/action/catalog";
return this;}
FilterController.prototype.id="FilterController";FilterController.prototype.filterCategoryId="";FilterController.prototype.filters=new Array();FilterController.prototype.filtersButtonsIdArray=new Array();FilterController.prototype.handlerUrl="";FilterController.prototype.filteredItemCount=0;FilterController.prototype.totalItemCount=0;FilterController.prototype.isGenerated=false;
FilterController.prototype.init=function(){}
FilterController.prototype.show=function(){
this.isDisplayed=true;
if(typeof(Catalog)!="undefined"){
this.isGenerated=true;
Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);
Catalog.loadCategory(Catalog.displayedCategoryId);}}
FilterController.prototype.hide=function(){
this.isDisplayed=false;}
FilterController.prototype.generate=function(categoryId){
if(this.isDisplayed){
this.filterCategoryId=categoryId;
var categoryDropDownElement=document.getElementById(this.id+"Category");var categoryArray=Catalog.categoryTreeArray;var filtersArray=this.filters[categoryId];var content="";var parentCategory=Catalog.getParentCategoryId(categoryId);
if(filtersArray!=undefined){
categoryDropDownElement.innerHTML="";
for(var i=0;i<categoryArray.length;i++){addItemToList(new Array(categoryArray[i]["CATEGORY_DESC"],categoryArray[i]["CATEGORY_ID"]),categoryDropDownElement);}
categoryDropDownElement.value=parentCategory;
if(document.getElementById(this.id+"Count")!=undefined){
this.totalItemCount=0;
for(var categoryIndex in categoryArray){if(categoryArray[categoryIndex]["CATEGORY_ID"]==parentCategory){for(var subcategoryIndex in categoryArray[categoryIndex]["CATEGORIES"]){if(categoryArray[categoryIndex]["CATEGORIES"][subcategoryIndex]["CATEGORY_ID"]==categoryId){this.totalItemCount=parseInt(categoryArray[categoryIndex]["CATEGORIES"][subcategoryIndex]["NUMBER_OF_ITEMS"]);break;}}
break;}}
this.filteredItemCount=Catalog.catalogArray[categoryId].length;}}
ParserUtils.applyTemplate(this.id+"Template",this.id+"Container",this);}}
FilterController.prototype.set=function(pCategoryId,pFilterDataArray){
if(pFilterDataArray!=undefined&&pCategoryId!=undefined){this.filters[pCategoryId]=pFilterDataArray;}
if(this.isDisplayed){this.generate(pCategoryId);}}
FilterController.prototype.reset=function(categoryId){
categoryId=(categoryId!=undefined?categoryId : Catalog.displayedCategoryId);
var i=0;var j=0;
if(this.filters[categoryId]!=undefined){
while(i<this.filters[categoryId].length){j=0;while(j<this.filters[categoryId][i]["valuesList"].length){this.filters[categoryId][i]["valuesList"][j]["sel"]="0";j++;}
i++;}
this.apply(categoryId);}}
FilterController.prototype.isFilterSelected=function(categoryId,typeIndex){
var isOneValueChecked=false;
for(var j=0;j<this.filters[categoryId][typeIndex]["valuesList"].length;j++){if(this.filters[categoryId][typeIndex]["valuesList"][j]["sel"]=="1"){isOneValueChecked=true;break;}}
return isOneValueChecked;}
FilterController.prototype.update=function(categoryId){
var parameters=new Array();parameters[parameters.length]=["catID",categoryId];
var serializedFilters=this.serialize(categoryId);if(serializedFilters!=""){parameters[parameters.length]=["filters",serializedFilters];}
this.sendRequest("getCollection",parameters);}
FilterController.prototype.apply=function(pCategoryId){
Catalog.loadCategory(pCategoryId);}
FilterController.prototype.setValue=function(pCategoryId,pFilterId,pFilterValue,pFilterSelected){
var i=0;var j=0;var isFound=false;
while(i<this.filters[pCategoryId].length&&!isFound){if(this.filters[pCategoryId][i]["id"]==pFilterId){j=0;while(j<this.filters[pCategoryId][i]["valuesList"].length&&!isFound){if(this.filters[pCategoryId][i]["valuesList"][j]["val"]==pFilterValue){this.filters[pCategoryId][i]["valuesList"][j]["sel"]=pFilterSelected;isFound=true;}
j++;}}
i++;}}
FilterController.prototype.serialize=function(pCategoryId){
var stringFilters="";var filterArray=this.filters[pCategoryId];var isNoFilterSelected=true;
if(filterArray!=undefined){for(var i=0;i<filterArray.length;i++){stringFilters+=(stringFilters!=""?"|" : "")+filterArray[i]["id"]+
"~"+filterArray[i]["name"]+
"~"+filterArray[i]["sort"]+
"~"+filterArray[i]["pres"];
for(var j=0;j<filterArray[i]["valuesList"].length;j++){stringFilters+="^"+filterArray[i]["valuesList"][j]["occu"]+
"~"+filterArray[i]["valuesList"][j]["val"]+
"~"+filterArray[i]["valuesList"][j]["sel"]+
"~"+filterArray[i]["valuesList"][j]["sort"]+
"~"+filterArray[i]["valuesList"][j]["dsort"];
if(filterArray[i]["valuesList"][j]["sel"]=="1"){isNoFilterSelected=false;}}}}
if(isNoFilterSelected){return "";}else{return encodeURIComponent(stringFilters);}}
FilterController.prototype.sendRequest=function(pActionType,pParams){
var requestParams=new Array();requestParams[requestParams.length]=["actionType",pActionType];requestParams[requestParams.length]=["getDataOnly","true"];requestParams=requestParams.concat(pParams);
det.sendRequest({serverUrl:Workspace.serverContext+"/action/"+pActionType,action:pActionType,parameters:requestParams,callingController:this});}
FilterController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED){if(attributes!=undefined&&attributes.response!=undefined){
if(attributes.response["filters"]!=undefined&&attributes.response["filters"]!=""&&attributes.response["catID"]!=undefined){this.set(attributes.response["catID"],attributes.response["filters"]);}}}}
function StorageSolutionsController(id){this.id=id;}
StorageSolutionsController.prototype.id="StorageSolutionsController";StorageSolutionsController.prototype.currentCatID=undefined;StorageSolutionsController.prototype.mainCategoryId="";StorageSolutionsController.prototype.catalogStorageCatArray=undefined;
StorageSolutionsController.prototype.init=function(){resource.applyProperties(this.id+"Properties",this);
if(Workspace.isNewSession){MapUtils.setMapValue("ModelProperties/defaultType","craftsman",resource._environmentMap);}
Workspace.events.addListener(Workspace.events.EVENT_CATALOG_CATEGORY_CHANGED,this);Workspace.events.throwEvent(Workspace.events.EVENT_CONTROLLER_INITIALIZED,this);}
StorageSolutionsController.prototype.loadCategory=function(categoryId){var isCurrentStorageSolutionCatID=false;
if(categoryId==this.mainCategoryId){if(this.currentCatID==undefined){if(State.get("storageCategory")!=undefined&&State.get("storageCategory")!="initial"){this.currentCatID=this.getRealCategoryId(State.get("storageCategory"));}else{this.currentCatID=this.getRealCategoryId("craftsman");}}categoryId=this.currentCatID;}
if(this.currentCatID!=categoryId&&this.catalogStorageCatArray[categoryId]!=undefined){
Workspace.message.displayMessage({"message":resource.get("storageSolutions.message"),"templateId":"messageConfirmationTemplate","duration":0,"jsActionYes":"Catalog.loadCategory("+categoryId+")","jsActionNo":"Workspace.message.hide('"+"messageObject"+Workspace.message.messageObjectCount+"')","isClosableOnClick":false});
}else{Catalog.loadCategory(categoryId);}}
StorageSolutionsController.prototype.catchEvent=function(eventKey,attributes){if(eventKey==Workspace.events.EVENT_CATALOG_CATEGORY_CHANGED&&attributes!=undefined){if(State.get("storageCategory")!=undefined&&Model.defaultType!=State.get("storageCategory")&&!Model.isExternalTryOnUsed){Model.defaultType=State.get("storageCategory");Catalog.loadCategory(this.getRealCategoryId(State.get("storageCategory")));return;}else{Model.isExternalTryOnUsed=false;}
if(this.currentCatID!=attributes.displayedCategoryId&&this.catalogStorageCatArray[attributes.displayedCategoryId]!=undefined){var oldCategoryID=this.currentCatID;this.currentCatID=attributes.displayedCategoryId;Model.defaultType=this.catalogStorageCatArray[this.currentCatID];State.set("storageCategory",Model.defaultType);if(oldCategoryID!=undefined)Model.putOnDefaultOutfit();}}}
StorageSolutionsController.prototype.getRealCategoryId=function(defaultTypeId){for(var categoryId in this.catalogStorageCatArray){if(this.catalogStorageCatArray[categoryId]==defaultTypeId){return categoryId;}}}
function ConfigController(pId){
this.id=pId;this.items=resource.get(this.id+"Items");this.labels=resource.get(this.id+"Labels");this.settings=resource.get(this.id+"Settings");}
ConfigController.prototype.id="ConfigController";ConfigController.prototype.isGenerated=false;
ConfigController.prototype.items=new Array();ConfigController.prototype.labels=new Array();ConfigController.prototype.layouts=new Array();
ConfigController.prototype.settings=new Array();ConfigController.prototype.selectedIndexArray=new Array();ConfigController.prototype.isInitialized=false;ConfigController.prototype.templateId="RoomConfigTemplate";
ConfigController.prototype.init=function(){
var element=undefined;var labelElement=undefined;var imageUrlMask=undefined;
resource.applyProperties(this.id+"Properties",this);}
ConfigController.prototype.show=function(){
if(!this.isGenerated){
Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);Workspace.events.addListener(Workspace.events.EVENT_MODEL_LAYOUT_CHANGED,this);
this.generate();}}
ConfigController.prototype.select=function(pAttributeName,pIndex){
var itemsToTryOn="";
this.selectedIndexArray[pAttributeName]=pIndex;
if(pAttributeName=="layout"&&typeof(Model)!="undefined"){Model.setLayout(this.items[Model.layoutId][pAttributeName][pIndex]["id"]);this.generate();}else if(this.getParentAttributeName(pAttributeName)!=pAttributeName){
var masterAttribute=this.getParentAttributeName(pAttributeName);var attIndex1=0;var attIndex2=0;
if(this.isMajorSubAttribute(masterAttribute,pAttributeName)){
var attIndex1=pIndex;var attIndex2=this.selectedIndexArray[ this.getMinorAttributeName(masterAttribute)];}else{
var attIndex1=this.selectedIndexArray[ this.getMajorAttributeName(masterAttribute)];var attIndex2=pIndex;}
itemsToTryOn=this.items[Model.layoutId][masterAttribute]["ids"][attIndex1][attIndex2];}else if(this.items[Model.layoutId][pAttributeName]!=undefined&&this.items[Model.layoutId][pAttributeName][pIndex]!=undefined){itemsToTryOn=this.items[Model.layoutId][pAttributeName][pIndex]["id"];}
Items.loadItemInfoFromGarments(itemsToTryOn.replace(/:[0-9]/g,"").split(","),"Model.tryOnItems('"+itemsToTryOn+"');");}
ConfigController.prototype.isCompoundAttribute=function(attributeName){
if(this.items[Model.layoutId][attributeName]!=undefined){
if(this.items[Model.layoutId][attributeName]["subAttributes"]!=undefined){return true;}else{return false;}}else{return false}
}
ConfigController.prototype.getParentAttributeName=function(attributeName){
for(var attrib in this.items[Model.layoutId]){if(attrib==attributeName){return attrib;}else{if(this.items[Model.layoutId][attrib]["subAttributes"]!=undefined){for(var indexSub in this.items[Model.layoutId][attrib]["subAttributes"]){if(this.items[Model.layoutId][attrib]["subAttributes"][indexSub]==attributeName){return attrib;}}}}}
}
ConfigController.prototype.isMajorSubAttribute=function(attributeName,subAttributeName){
var masterAttributeSection=this.items[Model.layoutId][attributeName]["subAttributes"];
if(masterAttributeSection!=undefined&&masterAttributeSection[0]==subAttributeName){return true;}else{return false;}
}
ConfigController.prototype.getMajorAttributeName=function(attributeName){
var masterAttributeSection=this.items[Model.layoutId][attributeName]["subAttributes"];
if(masterAttributeSection!=undefined){return masterAttributeSection[0];}else{return "";}}
ConfigController.prototype.getMinorAttributeName=function(attributeName){
var masterAttributeSection=this.items[Model.layoutId][attributeName]["subAttributes"];
if(masterAttributeSection!=undefined){return masterAttributeSection[1];}else{return "";}}
ConfigController.prototype.generate=function(isForced){
if(!this.isGenerated||isForced){ParserUtils.applyTemplate(this.templateId,this.id+"Container",this,this.id+".updateSelections(Model.content.allGarmentsArray);");this.isGenerated=true;}else{this.updateSelections(Model.content.allGarmentsArray);}}
ConfigController.prototype.updateSelections=function(pAllItemsArray){
var allItemAsString="|"+pAllItemsArray.join("|")+"|";
for(var attribute in this.items[Model.layoutId]){
if(this.isCompoundAttribute(attribute)==true){
var subAttribute1=this.items[Model.layoutId][attribute]["subAttributes"][0];var subAttribute2=this.items[Model.layoutId][attribute]["subAttributes"][1];
for(var sub1Index in this.items[Model.layoutId][attribute]["ids"]){for(var sub2Index in this.items[Model.layoutId][attribute]["ids"][sub1Index]){var currentId=this.items[Model.layoutId][attribute]["ids"][sub1Index][sub2Index];
var optionSubElement1=document.getElementById(this.id+"_"+subAttribute1+"_"+sub1Index);var optionSubElement2=document.getElementById(this.id+"_"+subAttribute2+"_"+sub2Index);
if(allItemAsString.indexOf("|"+currentId)>-1){
this.selectedIndexArray[ subAttribute1 ]=sub1Index;this.selectedIndexArray[ subAttribute2 ]=sub2Index;
break;}}}
for(var sub1Index in this.items[Model.layoutId][attribute]["ids"]){
var optionSubElement1=document.getElementById(this.id+"_"+subAttribute1+"_"+sub1Index);
if(optionSubElement1!=undefined&&optionSubElement1.className!='item'){this.setElementHighlight(optionSubElement1,"RoomConfig_"+subAttribute1+"_label",false);}}
for(var sub2Index in this.items[Model.layoutId][attribute]["ids"][0]){
var optionSubElement2=document.getElementById(this.id+"_"+subAttribute2+"_"+sub2Index);
if(optionSubElement2!=undefined &&optionSubElement2.className!='item'){this.setElementHighlight(optionSubElement2,"RoomConfig_"+subAttribute2+"_label",false);}}
var optionSubElement1=document.getElementById(this.id+"_"+subAttribute1+"_"+this.selectedIndexArray[ subAttribute1 ]);var optionSubElement2=document.getElementById(this.id+"_"+subAttribute2+"_"+this.selectedIndexArray[ subAttribute2 ]);
if(optionSubElement1!=undefined){this.setElementHighlight(optionSubElement1,"RoomConfig_"+subAttribute1+"_label",true);}
if(optionSubElement2!=undefined){this.setElementHighlight(optionSubElement2,"RoomConfig_"+subAttribute2+"_label",true);}
}else{
for(var i=0;i<this.items[Model.layoutId][attribute].length;i++){
var optionElement=document.getElementById(this.id+"_"+attribute+"_"+i);
if(optionElement!=undefined&&attribute=="layout"&&typeof(Model)!="undefined"){
if(Model.layoutIdArray[this.items[Model.layoutId][attribute][i]]==Model.layoutId){optionElement.className="item";}else{optionElement.className="itemSelected";}
}else{if(optionElement!=undefined&&allItemAsString.indexOf("|"+this.items[Model.layoutId][attribute][i]["id"])>-1){
this.setElementHighlight(optionElement,"RoomConfig_"+attribute+"_label",true);this.selectedIndexArray[ attribute ]=i;}else if(optionElement!=undefined){this.setElementHighlight(optionElement,"RoomConfig_"+attribute+"_label",false);}}}}}}
ConfigController.prototype.setElementHighlight=function(optionElement,labelName,isSelected){
var className="item";
if(isSelected){className="itemSelected";}
if(optionElement!=undefined){optionElement.className=className;optionElement.onmouseout=new Function("this.className='"+className+"';document.getElementById('"+labelName+"').innerHTML=''");optionElement.onmouseover=new Function("this.className='itemHighlight';document.getElementById('"+labelName+"').innerHTML=this.getAttribute('labelName')");}}
ConfigController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED){if(attributes!=undefined&&attributes.response!=undefined){
if(attributes.response["allGarmentIds"]!=undefined){
if(!this.isInitialized){this.generate();this.isInitialized=true;}
this.updateSelections(attributes.response["allGarmentIds"]);}}}
else if(eventKey==Workspace.events.EVENT_MODEL_LAYOUT_CHANGED){this.generate(true);}}
function RoomConfigController(pId){jsClass.extend(this,[ConfigController]);this.id=pId;this.items=resource.get("ConfigItems");this.labels=resource.get("ConfigLabels");this.settings=resource.get("ConfigSettings");}
RoomConfigController.prototype.id="RoomConfigController";RoomConfigController.prototype.items=new Array();RoomConfigController.prototype.labels=new Array();RoomConfigController.prototype.selectedIndexArray=new Array();
RoomConfigController.prototype.select=function(pAttributeName,pIndex){var itemsToTryOn="";this.selectedIndexArray[pAttributeName]=pIndex;
if(pAttributeName=="cabinetStyle"||pAttributeName=="cabinetColor")itemsToTryOn=this.items[Model.layoutId]["cabinetDoor"][this.selectedIndexArray["cabinetStyle"]][this.selectedIndexArray["cabinetColor"]];else if(pAttributeName=="handleStyle"||pAttributeName=="handleColor")itemsToTryOn=this.items[Model.layoutId]["cabinetHandle"][this.selectedIndexArray["handleStyle"]][this.selectedIndexArray["handleColor"]];else if(RoomConfig.items[Model.layoutId][pAttributeName]!=undefined&&RoomConfig.items[Model.layoutId][pAttributeName][pIndex]!=undefined){itemsToTryOn=RoomConfig.items[Model.layoutId][pAttributeName][pIndex]["id"];}
Items.loadItemInfoFromGarments(itemsToTryOn.replace(/:[0-9]/g,"").split(","),"Model.tryOnItems('"+itemsToTryOn+"');");}
RoomConfigController.prototype.updateSelections=function(pAllItemsArray){var allItemAsString="|"+pAllItemsArray.join("|")+"|";
for(var j=0;j<this.items[Model.layoutId]["cabinetDoor"][0].length;j++){optionElement=document.getElementById(this.id+"_cabinetColor_"+j);if(optionElement!=undefined){optionElement.className="item";optionElement.onmouseout=new Function("this.className='item';document.getElementById('RoomConfig_cabinetColor_label').innerHTML='';");optionElement.onmouseover=new Function("this.className='itemHighlight';document.getElementById('RoomConfig_cabinetColor_label').innerHTML=this.getAttribute('labelName');");}}
for(var j=0;j<this.items[Model.layoutId]["cabinetHandle"][0].length;j++){optionElement=document.getElementById(this.id+"_handleColor_"+j);if(optionElement!=undefined){optionElement.className="item";optionElement.onmouseout=new Function("this.className='item';document.getElementById('RoomConfig_handleColor_label').innerHTML='';");optionElement.onmouseover=new Function("this.className='itemHighlight';document.getElementById('RoomConfig_handleColor_label').innerHTML=this.getAttribute('labelName');");}}
for(var attribute in this.items[Model.layoutId]){for(var i=0;i<this.items[Model.layoutId][attribute].length;i++){
if(attribute=="cabinetDoor"){var j=0;
optionElement=document.getElementById(this.id+"_cabinetStyle_"+i);if(optionElement!=undefined){optionElement.className="item";optionElement.onmouseout=new Function("this.className='item';document.getElementById('RoomConfig_cabinetStyle_label').innerHTML='';");optionElement.onmouseover=new Function("this.className='itemHighlight';document.getElementById('RoomConfig_cabinetStyle_label').innerHTML=this.getAttribute('labelName');");}optionElement=undefined;
while(j<this.items[Model.layoutId][attribute][i].length&&optionElement==undefined){if(allItemAsString.indexOf("|"+this.items[Model.layoutId]["cabinetDoor"][i][j]+"|")>-1){
optionElement=document.getElementById(this.id+"_cabinetStyle_"+i);if(optionElement!=undefined){optionElement.className="itemSelected";optionElement.onmouseout=new Function("this.className='itemSelected';document.getElementById('RoomConfig_cabinetStyle_label').innerHTML='';");optionElement.onmouseover=new Function("this.className='itemSelected';document.getElementById('RoomConfig_cabinetStyle_label').innerHTML=this.getAttribute('labelName');");}
optionElement=document.getElementById(this.id+"_cabinetColor_"+j);if(optionElement!=undefined){optionElement.className="itemSelected";optionElement.onmouseout=new Function("this.className='itemSelected';document.getElementById('RoomConfig_cabinetColor_label').innerHTML='';");optionElement.onmouseover=new Function("this.className='itemSelected';document.getElementById('RoomConfig_cabinetColor_label').innerHTML=this.getAttribute('labelName');");}
this.selectedIndexArray["cabinetStyle"]=i;this.selectedIndexArray["cabinetColor"]=j;}j++;}}
else if(attribute=="cabinetHandle"){var j=0;
optionElement=document.getElementById(this.id+"_handleStyle_"+i);if(optionElement!=undefined){optionElement.className="item";optionElement.onmouseout=new Function("this.className='item';document.getElementById('RoomConfig_handleStyle_label').innerHTML='';");optionElement.onmouseover=new Function("this.className='itemHighlight';document.getElementById('RoomConfig_handleStyle_label').innerHTML=this.getAttribute('labelName');");}optionElement=undefined;optionElement=document.getElementById(this.id+"_handleColor_"+i);if(optionElement!=undefined){optionElement.className="item";optionElement.onmouseout=new Function("this.className='item';document.getElementById('RoomConfig_handleColor_label').innerHTML='';");optionElement.onmouseover=new Function("this.className='itemHighlight';document.getElementById('RoomConfig_handleColor_label').innerHTML=this.getAttribute('labelName');");}optionElement=undefined;
while(j<this.items[Model.layoutId][attribute][i].length&&optionElement==undefined){if(allItemAsString.indexOf("|"+this.items[Model.layoutId]["cabinetHandle"][i][j]+"|")>-1){optionElement=document.getElementById(this.id+"_handleStyle_"+i);if(optionElement!=undefined){optionElement.className="itemSelected";optionElement.onmouseout=new Function("this.className='itemSelected';document.getElementById('RoomConfig_handleStyle_label').innerHTML='';");optionElement.onmouseover=new Function("this.className='itemSelected';document.getElementById('RoomConfig_handleStyle_label').innerHTML=this.getAttribute('labelName');");}
optionElement=document.getElementById(this.id+"_handleColor_"+j);if(optionElement!=undefined){optionElement.className="itemSelected";optionElement.onmouseout=new Function("this.className='itemSelected';document.getElementById('RoomConfig_handleColor_label').innerHTML='';");optionElement.onmouseover=new Function("this.className='itemSelected';document.getElementById('RoomConfig_handleColor_label').innerHTML=this.getAttribute('labelName');");}
this.selectedIndexArray["handleStyle"]=i;this.selectedIndexArray["handleColor"]=j;}j++;}}else{
if(attribute!="handleColor"&&attribute!="handleStyle"&&attribute!="cabinetStyle"&&attribute!="cabinetColor"){var optionElement=document.getElementById(this.id+"_"+attribute+"_"+i);if(optionElement!=undefined&&allItemAsString.indexOf("|"+this.items[Model.layoutId][attribute][i]+"|")>-1){optionElement.className="itemSelected";optionElement.onmouseout=new Function("this.className='itemSelected';document.getElementById('RoomConfig_"+attribute+"_label').innerHTML='';");optionElement.onmouseover=new Function("this.className='itemSelected';document.getElementById('RoomConfig_"+attribute+"_label').innerHTML=this.getAttribute('labelName');");}else if(optionElement!=undefined){optionElement.className="item";optionElement.onmouseout=new Function("this.className='item';document.getElementById('RoomConfig_"+attribute+"_label').innerHTML='';");optionElement.onmouseover=new Function("this.className='itemHighlight';document.getElementById('RoomConfig_"+attribute+"_label').innerHTML=this.getAttribute('labelName');");}this.selectedIndexArray[ attribute ]=i;}}}}
for(index in this.layouts){var layoutId=this.layouts[index]["id"];var layoutLabel=this.layouts[index]["label"];var optionElementId=this.id+"_layout_"+layoutId;var optionElement=document.getElementById(optionElementId);if(optionElement!=undefined){if(Model.layoutId==layoutId){optionElement.className="itemSelected";optionElement.onmouseout=new Function("this.className='itemSelected';document.getElementById('RoomConfig_layout_label').innerHTML='';");optionElement.onmouseover=new Function("this.className='itemSelected';document.getElementById('RoomConfig_layout_label').innerHTML='"+layoutLabel+"';");}else{optionElement.className="item";optionElement.onmouseout=new Function("this.className='item';document.getElementById('RoomConfig_layout_label').innerHTML='';");optionElement.onmouseover=new Function("this.className='itemHighlight';document.getElementById('RoomConfig_layout_label').innerHTML='"+layoutLabel+"';");}}}}
function ECardController(id){jsClass.extend(this,[QuestionnaireController]);
this.id=id;}
ECardController.prototype.id="ECardController";ECardController.prototype.eCardId="";ECardController.prototype.domain="";ECardController.prototype.pickupLink="";ECardController.prototype.mailServerSenderAdress="";ECardController.prototype.isSendConfirmation=true;ECardController.prototype.isSendingConfirmation=false;
ECardController.prototype.init=function(){
this.super_QuestionnaireController_init();
if(this.pickupLink==""){this.pickupLink=location.href+"&ecardid=@ecard_id@";}
Workspace.events.addListener(Workspace.events.EVENT_PAGE_LOADED,this);}
ECardController.prototype.show=function(){
this.answerMap["message"]=this.defaultAnswersMap["message"];this.answerMap["senderName"]=this.defaultAnswersMap["senderName"];this.answerMap["subject"]=this.defaultAnswersMap["subject"];
this.setAnswersMap(this.answerMap);
if(!this.isGenerated){this.isGenerated=true;
ParserUtils.preloadTemplate(this.id+"EmailTemplate");ParserUtils.preloadTemplate(this.id+"EmailConfirmationTemplate");ParserUtils.applyTemplate(this.id+"Template",this.id+"Container",this,this.id+".initFields()");
Workspace.events.addListener(Workspace.events.EVENT_MODEL_ATTRIBUTES_CHANGED,this);}}
ECardController.prototype.clear=function(){
var emptyMap=new Array();
for(var fieldId in this.fieldObjectMap){emptyMap[fieldId]="";}
this.setAnswersMap(emptyMap,false);}
ECardController.prototype.send=function(){
if(this.isAllFieldsValid()){this.sendRequest("sendEcards",this.getEcardRequestParameters());
}else{
this.updateFields();var foundInvalidField=false;}}
ECardController.prototype.sendRequest=function(actionType,params){
det.sendRequest({serverUrl:Workspace.serverContext+"/action/"+actionType,parameters:params,callingController:this});}
ECardController.prototype.getEcardRequestParameters=function(){
var params=new Array();var answersMap=this.getAnswersMap();var ecardIndex=0;
answersMap["link"]=this.pickupLink;answersMap["modelAttributes"]=ModelQuestionnaire.getAnswersMap();answersMap["onMyModelGarments"]=Model.content.allGarmentsArray;
var eCardAsString=encodeURIComponent(MapUtils.toJSON(answersMap));
if(answersMap["recipientEmail1"]!=""){
params[params.length]=["ecards["+ecardIndex+"].from",this.mailServerSenderAdress];params[params.length]=["ecards["+ecardIndex+"].subject",answersMap["subject"]];params[params.length]=["ecards["+ecardIndex+"].to",answersMap["recipientEmail1"]];params[params.length]=["ecards["+ecardIndex+"].message",encodeURIComponent(ParserUtils.parseTemplate(this.id+"EmailTemplate",answersMap))];params[params.length]=["ecards["+ecardIndex+"].data",eCardAsString];params[params.length]=["ecards["+ecardIndex+"].content_type","text/html;charset=UTF-8"];ecardIndex++;}
if(answersMap["recipientEmail2"]!=""){params[params.length]=["ecards["+ecardIndex+"].from",this.mailServerSenderAdress];params[params.length]=["ecards["+ecardIndex+"].subject",answersMap["subject"]];params[params.length]=["ecards["+ecardIndex+"].to",answersMap["recipientEmail2"]];params[params.length]=["ecards["+ecardIndex+"].message",encodeURIComponent(ParserUtils.parseTemplate(this.id+"EmailTemplate",answersMap))];params[params.length]=["ecards["+ecardIndex+"].data",eCardAsString];params[params.length]=["ecards["+ecardIndex+"].content_type","text/html;charset=UTF-8"];ecardIndex++;}
if(answersMap["recipientEmail3"]!=""){params[params.length]=["ecards["+ecardIndex+"].from",this.mailServerSenderAdress];params[params.length]=["ecards["+ecardIndex+"].subject",answersMap["subject"]];params[params.length]=["ecards["+ecardIndex+"].to",answersMap["recipientEmail3"]];params[params.length]=["ecards["+ecardIndex+"].message",encodeURIComponent(ParserUtils.parseTemplate(this.id+"EmailTemplate",answersMap))];params[params.length]=["ecards["+ecardIndex+"].data",eCardAsString];params[params.length]=["ecards["+ecardIndex+"].content_type","text/html;charset=UTF-8"];ecardIndex++;}
params[params.length]=["isECardMessage",true];
return params;}
ECardController.prototype.getConfirmationRequestParameters=function(){
var params=new Array();var answersMap=this.getAnswersMap();var ecardIndex=0;
answersMap["link"]=this.pickupLink;answersMap["modelAttributes"]=ModelQuestionnaire.getAnswersMap();answersMap["onMyModelGarments"]=Model.content.allGarmentsArray;
var eCardAsString=encodeURIComponent(MapUtils.toJSON(answersMap));
params[params.length]=["ecards["+ecardIndex+"].from",this.mailServerSenderAdress];params[params.length]=["ecards["+ecardIndex+"].subject",answersMap["subject"]];params[params.length]=["ecards["+ecardIndex+"].to",answersMap["senderEmail"]];params[params.length]=["ecards["+ecardIndex+"].message",encodeURIComponent(ParserUtils.parseTemplate(this.id+"EmailConfirmationTemplate",answersMap))];params[params.length]=["ecards["+ecardIndex+"].data",eCardAsString];params[params.length]=["ecards["+ecardIndex+"].content_type","text/html;charset=UTF-8"];
return params;}
ECardController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED&&attributes.callingController==this){if(attributes!=undefined&&attributes.response!=undefined){
if(attributes.response["ecardIds"]!=undefined){
if(attributes.parametersMap["isECardMessage"]!=undefined){
Workspace.events.throwEvent(Workspace.events.EVENT_ECARD_SENT,attributes);
if(this.isSendConfirmation){this.sendRequest("sendEcards",this.getConfirmationRequestParameters());}}
}else if(attributes.response["ecardData"]!=undefined){this.displayECard(attributes.response["ecardData"]);}}
}else if(eventKey==Workspace.events.EVENT_PAGE_LOADED&&Workspace.query.ecardid!=undefined){this.retreive(Workspace.query.ecardid);}else if(eventKey==Workspace.events.EVENT_MODEL_ATTRIBUTES_CHANGED){this.show();}}
ECardController.prototype.retreive=function(eCardId){
if(eCardId!=undefined&&eCardId!=""){this.sendRequest("getEcard",[["ecardId",eCardId]]);}}
ECardController.prototype.displayECard=function(attributes){
}
function EMailController(id){this.id=id;}
EMailController.prototype.id="EMailController";EMailController.prototype.mailServerSenderAdress="";EMailController.prototype.parametersMap=undefined;EMailController.prototype.defaultParametersMap=undefined;EMailController.prototype.template=undefined;
EMailController.prototype.init=function(){
this.parametersMap=new Array();   
resource.applyProperties(this.id+"Properties",this);this.parametersMap=this.defaultParametersMap;
Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);}
EMailController.prototype.send=function(emailReason){
this.template=this.id+emailReason+"Template";ParserUtils.preloadTemplate(this.template,this.id+"._postloadTemplateSend()");}
EMailController.prototype._postloadTemplateSend=function(){
this.sendRequest("sendEcards",this.getEMailRequestParameters());}
EMailController.prototype.sendRequest=function(actionType,params){
det.sendRequest({serverUrl:Workspace.serverContext+"/action/"+actionType,parameters:params,callingController:this});}
EMailController.prototype.getEMailRequestParameters=function(){
var params=new Array();var ecardIndex=0;var eCardAsString="";
this.parametersMap["recipientEmail"]=ProfileQuestionnaire.getAnswersMap()["Email"];
eCardAsString=encodeURIComponent(MapUtils.toJSON(this.parametersMap));
params[params.length]=["ecards["+ecardIndex+"].from",this.mailServerSenderAdress];params[params.length]=["ecards["+ecardIndex+"].subject",this.parametersMap["subject"]];params[params.length]=["ecards["+ecardIndex+"].to",this.parametersMap["recipientEmail"]];params[params.length]=["ecards["+ecardIndex+"].message",encodeURIComponent(ParserUtils.parseTemplate(this.template,this.parametersMap))];params[params.length]=["ecards["+ecardIndex+"].data",eCardAsString];params[params.length]=["ecards["+ecardIndex+"].content_type","text/html;charset=UTF-8"];
return params;}
EMailController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED&&attributes.callingController==this){if(attributes!=undefined&&attributes.response!=undefined){Workspace.events.throwEvent(Workspace.events.EVENT_EMAIL_SENT,attributes);}}}
function FavoritesController(pId){
this.id=pId;this.handlerUrl=Workspace.serverContext+"/action/";
return this;}
FavoritesController.prototype.id="FavoritesController";FavoritesController.prototype.handlerUrl="";FavoritesController.prototype.itemsArray=new Array();FavoritesController.prototype.outfitsArray=new Array();FavoritesController.prototype.outfitsThumbnailMap=new Array();FavoritesController.prototype.itemElementId="";FavoritesController.prototype.outfitElementId="";FavoritesController.prototype.generatedItemsArray=new Array();FavoritesController.prototype.generatedOutfitsArray=new Array();FavoritesController.prototype.isInitialized=false;FavoritesController.prototype.isGenerated=false;FavoritesController.prototype.swatchUrl="";FavoritesController.prototype.thumbnailPrefix="";FavoritesController.prototype.thumbnailSuffix="";FavoritesController.prototype.outfitThumbnailWidth="";FavoritesController.prototype.outfitThumbnailHeight="";FavoritesController.prototype.isRemoveIncompatibleItems=false;
FavoritesController.prototype.init=function(){
resource.applyProperties(this.id+"Properties",this);
Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);
this.itemElementId=this.id+"ItemsContainer";this.outfitElementId=this.id+"OutfitsContainer";
this.isInitialized=true;}
FavoritesController.prototype.show=function(){
if(Workspace.user.isSignedIn&&!Workspace.user.isAuthenticated){Workspace.events.addEventScript(Workspace.events.EVENT_USER_AUTHENTICATED,this.id+".show()",true);Workspace.user.displayAuthentication();}else if(!this.isGenerated){
Workspace.events.addListener(Workspace.events.EVENT_USER_STATE_CHANGE,this);Workspace.events.addListener(Workspace.events.EVENT_BODYSET_CHANGED,this);
this.load();this.isGenerated=true;}}
FavoritesController.prototype.load=function(){
if(Workspace.user.isSignedIn&&Workspace.user.isAuthenticated){this.sendRequest("getFavorites");}else{this.generate();}}
FavoritesController.prototype.generate=function(){
if(document.getElementById(this.itemElementId)!=undefined&&document.getElementById(this.outfitElementId)!=undefined){
document.getElementById(this.itemElementId).innerHTML="";document.getElementById(this.outfitElementId).innerHTML="";
this.generatedItemsArray=new Array();this.generatedOutfitsArray=new Array();
this.generateItemsRange(0,this.itemsArray.length);this.generateOutfitsRange(0,this.outfitsArray.length);
if(!Workspace.user.isSignedIn||!Workspace.user.isAuthenticated){document.getElementById(this.itemElementId).innerHTML=resource.get("Vdr.Favorites.NotSignedIn");document.getElementById(this.outfitElementId).innerHTML=resource.get("Vdr.Favorites.NotSignedIn");}
if(Workspace.user.isAuthenticated&&this.itemsArray.length==0){document.getElementById(this.itemElementId).innerHTML=resource.get("Vdr.Favorites.NoFavoriteItems");}
if(Workspace.user.isAuthenticated&&this.outfitsArray.length==0){document.getElementById(this.outfitElementId).innerHTML=resource.get("Vdr.Favorites.NoFavoriteOutfits");}}else{log.error("Favorites HTML elements are not defined in the template.")}}
FavoritesController.prototype.clear=function(){
this.itemsArray=new Array();this.outfitsArray=new Array();this.outfitsThumbnailMap=new Array();this.generate();}
FavoritesController.prototype.generateItemsRange=function(pStartIndex,pEndIndex){
ParserUtils.preloadTemplate(this.id+"ItemTemplate",this.id+"._generateItemsRange("+pStartIndex+","+pEndIndex+")");}
FavoritesController.prototype._generateItemsRange=function(pStartIndex,pEndIndex){
var itemsElement=document.getElementById(this.itemElementId);var content="";
for(var i=pStartIndex;i<pEndIndex;i++){
if(this.itemsArray[i]!=undefined&&this.generatedItemsArray[i]==undefined){
if(!Items.isFallback(this.itemsArray[i])){content+=this.getItemHTML(Items.getItemFromItemId(this.itemsArray[i]),i);}
this.generatedItemsArray[i]=true;}}
itemsElement.innerHTML+=content;}
FavoritesController.prototype.generateOutfitsRange=function(pStartIndex,pEndIndex){
ParserUtils.preloadTemplate(this.id+"OutfitItemTemplate","ParserUtils.preloadTemplate('"+this.id+"OutfitTemplate','"+this.id+"._generateOutfitsRange("+pStartIndex+","+pEndIndex+")')");}
FavoritesController.prototype._generateOutfitsRange=function(pStartIndex,pEndIndex){
var outfitsElement=document.getElementById(this.outfitElementId);var content="";
for(var i=pStartIndex;i<pEndIndex;i++){
if(this.outfitsArray[i]!=undefined&&this.generatedOutfitsArray[i]==undefined&&this.outfitsArray[i]["items"].length>0){
content+=this.getOutfitHTML(this.outfitsArray[i],i);this.generatedOutfitsArray[i]=true;}}
outfitsElement.innerHTML+=content;}
FavoritesController.prototype.getItemHTML=function(pItem,index){
var attributes=MapUtils.getClone(pItem);attributes["index"]=index;attributes["controllerId"]=this.id;
return ParserUtils.parseTemplate(this.id+"ItemTemplate",attributes);}
FavoritesController.prototype.getOutfitHTML=function(pOutfit,index){
var itemsContent="";var attributes=undefined;var outfitItems=MapUtils.getClone(pOutfit["items"]);var isOutfitBodysetCompatible=true;var isItemBodysetCompatible=false;var count=0;var itemId=undefined;
for(var i=0;i<outfitItems.length;i++){
itemId=outfitItems[i]["itemId"];
if(!Items.isFallback(itemId)){
attributes=MapUtils.getClone(Items.getItemFromItemId(itemId));
isItemBodysetCompatible=Items.isCompatible(itemId);if(!isItemBodysetCompatible){isOutfitBodysetCompatible=false;}
attributes["outfitIndex"]=index;attributes["outfitCount"]=this.outfitsArray.length;attributes["itemIndex"]=count;attributes["itemCount"]=outfitItems.length;attributes["controllerId"]=this.id;attributes["garmentId"]=outfitItems[i]["garmentId"];
itemsContent+=ParserUtils.parseTemplate(this.id+"OutfitItemTemplate",attributes);count++;}}
attributes=MapUtils.getClone(pOutfit);
if(Model.rendererType=="RT3D"){attributes["thumbnailUrl"]=this.getUpdatedMPSThumnailUrl(decodeURIComponent(this.outfitsThumbnailMap[attributes["outfitId"]]),attributes["layoutId"]);}
else{attributes["thumbnailUrl"]=decodeURIComponent(this.outfitsThumbnailMap[attributes["outfitId"]]);}
attributes["outfitIndex"]=index;attributes["outfitCount"]=this.outfitsArray.length;attributes["itemCount"]=outfitItems.length;attributes["controllerId"]=this.id;attributes["itemsContent"]=itemsContent;attributes["isBodysetCompatible"]=isOutfitBodysetCompatible;
return ParserUtils.parseTemplate(this.id+"OutfitTemplate",attributes);}
FavoritesController.prototype.getUpdatedMPSThumnailUrl=function(thumbUrl,layoutId){
var imageUrlStart="";var imageUrlOrigParams="";
var presetCamera=new Camera();
presetCamera.setCameraFrom(Model.camera);
CameraControl.setCameraPresetState(presetCamera,0,layoutId);
if(thumbUrl.indexOf("?")>-1){
imageUrlStart=thumbUrl.split("?")[0];imageUrlOrigParams=thumbUrl.split("?")[1];
var addedParams="";
addedParams+="&"+presetCamera.getMPSString();
thumbUrl=imageUrlStart+"?"+"m=r"+"&"+imageUrlOrigParams+addedParams;}
return thumbUrl;}
FavoritesController.prototype.addItem=function(pItemId){
if(!Workspace.user.isSignedIn){Workspace.message.displayMessage(resource.get("Vdr.Favorites.NotSignedIn"));
}else if(!Workspace.user.isAuthenticated){
Workspace.events.addEventScript(Workspace.events.EVENT_USER_AUTHENTICATED,this.id+".addItem('"+pItemId+"')",true);Workspace.user.displayAuthentication();}else if(pItemId!=undefined&&pItemId!=""){this.sendRequest("addFavoriteItem",[["itemId",pItemId]]);}}
FavoritesController.prototype.deleteItem=function(pItemId,pForceFlag){
if(!Workspace.user.isSignedIn){Workspace.message.displayMessage(resource.get("Vdr.Favorites.NotSignedIn"));
}else if(!Workspace.user.isAuthenticated){Workspace.user.displayAuthentication(this.id+".deleteItem('"+pItemId+"',"+pForceFlag+")");}else if(pItemId!=undefined&&pItemId!=""){
if(pForceFlag){this.sendRequest("deleteFavoriteItem",[["itemId",pItemId]]);}else{
Workspace.message.displayMessage({"message":resource.get("Vdr.Favorites.confirmDeleteItem"),"templateId":"messageConfirmationTemplate","jsActionYes":this.id+".deleteItem('"+pItemId+"',true)","jsActionNo":"void(0)","isClosableOnClick":false});}}}
FavoritesController.prototype.deleteAllItems=function(){}
FavoritesController.prototype.addOutfit=function(){
if(!Workspace.user.isSignedIn){Workspace.message.displayMessage(resource.get("Vdr.Favorites.NotSignedIn"));
}else if(!Workspace.user.isAuthenticated){
Workspace.events.addEventScript(Workspace.events.EVENT_USER_AUTHENTICATED,this.id+".sendRequest('addFavoriteOutfit',new Array())",true);Workspace.user.displayAuthentication();}else{this.sendRequest("addFavoriteOutfit",new Array());}}
FavoritesController.prototype.deleteOutfit=function(pOutfitId,pForceFlag){
if(Workspace.user.isAuthenticated){if(pOutfitId!=undefined&&pOutfitId!=""){
if(pForceFlag){this.sendRequest("deleteFavoriteOutfit",[["outfitId",pOutfitId]]);}else{
Workspace.message.displayMessage({"message":resource.get("Vdr.Favorites.confirmDeleteOutfit"),"templateId":"messageConfirmationTemplate","jsActionYes":this.id+".deleteOutfit('"+pOutfitId+"',true)","jsActionNo":"void(0)","isClosableOnClick":false});}}}else{
Workspace.user.displayAuthentication(this.id+".deleteOutfit('"+pOutfitId+"')");}}
FavoritesController.prototype.deleteAllOutfit=function(){}
FavoritesController.prototype.sendRequest=function(pActionType,pParams){
var requestParams=new Array();
requestParams[requestParams.length]=["IMAGE_WIDTH",this.outfitThumbnailWidth];requestParams[requestParams.length]=["IMAGE_HEIGHT",this.outfitThumbnailHeight];
if(pParams!=undefined){requestParams=requestParams.concat(pParams);}
det.sendRequest({serverUrl:this.handlerUrl+pActionType,action:pActionType,parameters:requestParams,callingController:this});}
FavoritesController.prototype.updateItemCache=function(){
var itemIdList=new Array();
itemIdList=MapUtils.getClone(this.itemsArray);
for(var outfitIndex in this.outfitsArray){for(var itemIndex in this.outfitsArray[outfitIndex]["items"]){itemIdList.push(this.outfitsArray[outfitIndex]["items"][itemIndex]["itemId"]);}}
Items.loadItemInfo(itemIdList,this.id+".filterItems()");}
FavoritesController.prototype.filterItems=function(){
var itemId=undefined;
var tempFilterItemsArray=new Array();
for(var itemIndex in this.itemsArray){
itemId=this.itemsArray[itemIndex];
if((!this.isRemoveIncompatibleItems||(this.isRemoveIncompatibleItems&&Items.isCompatible(itemId)))){tempFilterItemsArray[tempFilterItemsArray.length]=this.itemsArray[itemIndex];}}
this.itemsArray=tempFilterItemsArray;
var tempFilterOutfitsItemsArray=undefined;
for(var outfitIndex in this.outfitsArray){
tempFilterOutfitsItemsArray=new Array();
for(var itemIndex in this.outfitsArray[outfitIndex]["items"]){
itemId=this.outfitsArray[outfitIndex]["items"][itemIndex]["itemId"];
if((!this.isRemoveIncompatibleItems||(this.isRemoveIncompatibleItems&&Items.isCompatible(itemId)))){tempFilterOutfitsItemsArray[tempFilterOutfitsItemsArray.length]=this.outfitsArray[outfitIndex]["items"][itemIndex];}}
this.outfitsArray[outfitIndex]["items"]=tempFilterOutfitsItemsArray;}
this.generate();}
FavoritesController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED&&attributes.callingController==this){if(attributes!=undefined&&attributes.response!=undefined){
if(attributes.response["favoriteItem"]!=undefined){
this.itemsArray=attributes.response["favoriteItem"];this.outfitsArray=attributes.response["favoriteOutfit"];this.outfitsThumbnailMap=attributes.response["favoriteOutfitsThumnails"];
this.updateItemCache();}else{if(resource.get(attributes.response["errorCode"])!=""){
}else{
this.clear();}}
if((attributes["action"]=="addFavoriteItem"||attributes["action"]=="addFavoriteOutfit")&&attributes.response["errorCode"]==undefined){Workspace.events.throwEvent(Workspace.events.EVENT_FAVORITES_ADDED,attributes);}else if(attributes["action"]=="deleteFavoriteItem"||attributes["action"]=="deleteFavoriteOutfit"){Workspace.events.throwEvent(Workspace.events.EVENT_FAVORITES_REMOVED,attributes);}}
}else if(eventKey==Workspace.events.EVENT_USER_STATE_CHANGE){if(attributes!=undefined&&attributes.isSignedIn&&attributes.isAuthenticated){
this.load();}else{this.clear();}
}else if(eventKey==Workspace.events.EVENT_BODYSET_CHANGED){
this.load();}}
FavoritesController.prototype.tryOnOutfit=function(outfitId){
var garmentIdArray=new Array();var garment=undefined;var garmentId="";
for(var outfitIndex in this.outfitsArray){
if(this.outfitsArray[outfitIndex]["outfitId"]==outfitId){
for(var garmentIndex in this.outfitsArray[outfitIndex]["items"]){
garment=this.outfitsArray[outfitIndex]["items"][garmentIndex];garmentId=garment["garmentId"]+(garment["instanceId"]!=undefined?":"+garment["instanceId"] : "");garmentIdArray.push(garmentId);}
if(this.outfitsArray[outfitIndex]["layoutId"]!=undefined){Model.setLayoutId(this.outfitsArray[outfitIndex]["layoutId"],false);}
var params=new Array();params[params.length]=["defaultType",""];params[params.length]=["layoutId",Model.layoutId];
Model.setContent(garmentIdArray.join(","),params);
break;}}}
function FitRatingController(id){
this.id=id;
this.templateElementId=this.id+"Template";this.containerElementId=this.id+"Container";}
FitRatingController.prototype.SIZE_RECOMMENDED="BESTSIZE";FitRatingController.prototype.SIZE_ONE_DOWN="SIZE1UP";FitRatingController.prototype.SIZE_ONE_UP="SIZE1DOWN";FitRatingController.prototype.SIZE_LENGTH_DOWN="SIZE2UP";FitRatingController.prototype.SIZE_LENGTH_UP="SIZE2DOWN";
FitRatingController.prototype.id="FitRatingController";FitRatingController.prototype.isInitialized=false;FitRatingController.prototype.isEnabled=true;FitRatingController.prototype.isGenerated=false;FitRatingController.prototype.handlerUrl=undefined;FitRatingController.prototype.fitRating=undefined;FitRatingController.prototype.templateElementId=undefined;FitRatingController.prototype.containerElementId=undefined;FitRatingController.prototype.garmentId=undefined;FitRatingController.prototype.isDisplayOnExternalFitDetails=true;FitRatingController.prototype.fitMeasurementsSerialized=undefined;FitRatingController.prototype.supportedPopulations="F,M";FitRatingController.prototype.errorCode=undefined;
FitRatingController.prototype.init=function(){
resource.applyProperties(this.id+"Properties",this);
this.isInitialized=true;this.handlerUrl=Workspace.serverContext+"/action/fit";
if(this.supportedPopulations.indexOf(Workspace.population)==-1){this.disable();}}
FitRatingController.prototype.show=function(){
if(!this.isGenerated){this.isGenerated=true;
Workspace.events.addListener(Workspace.events.EVENT_ONMYMODEL_ITEM_SELECTED,this);Workspace.events.addListener(Workspace.events.EVENT_FIT_ATTRIBUTES_CHANGED,this);Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);Workspace.events.addListener(Workspace.events.EVENT_PAGE_LOADED,this);Workspace.events.addListener(Workspace.events.EVENT_USER_STATE_CHANGE,this);}
if(typeof(OnMyModel)!="undefined"){this.getItemRating(Model.content.selectedItemId);}}
FitRatingController.prototype.getRating=function(garmentId,templateElementId,containerElementId,sizeModifier){
if(this.isInitialized&&this.isEnabled){
this.templateElementId=(templateElementId!=undefined?templateElementId : this.templateElementId);this.containerElementId=(containerElementId!=undefined?containerElementId : this.containerElementId);this.garmentId=(garmentId!=undefined?garmentId : this.garmentId);
this.fitMeasurementsSerialized="";
if(typeof(FitQuestionnaire)!="undefined"&&FitQuestionnaire!=undefined&&FitQuestionnaire.isAllFieldsValid()&&FitQuestionnaire.isLoaded){
this.fitMeasurementsSerialized=MapUtils.toString(FitQuestionnaire.getAnswersMap(),"=",",");}
if(this.garmentId!=""&&this.garmentId!=undefined&&(this.fitMeasurementsSerialized!=""||Workspace.user.isSignedIn)){
var params=new Array();params[params.length]=["garmentId",this.garmentId];params[params.length]=["sizeType",(sizeModifier!=undefined?sizeModifier : this.SIZE_RECOMMENDED)]
if(!Workspace.user.isSignedIn&&this.fitMeasurementsSerialized!=""){params[params.length]=["measurements",this.fitMeasurementsSerialized];}
this.onLoading();this.sendRequest("getDetails",params);}else{
this.fitRating=undefined;this.generate();}}}
FitRatingController.prototype.getItemRating=function(itemId){
var itemInfo=Items.getItemFromItemId(itemId);
if(itemInfo!=undefined){this.getRating(itemInfo["GARMENTS"][0]["ID_GARMENT"]);}else{this.getRating("");}}
FitRatingController.prototype.setData=function(fitRating){
this.fitRating=undefined;
for(var garmentId in fitRating){this.fitRating=fitRating[garmentId]
break;}
this.generate();}
FitRatingController.prototype.showSize=function(sizeModifier){
this.getRating(this.garmentId,this.templateElementId,this.containerElementId,sizeModifier);}
FitRatingController.prototype.sendRequest=function(actionType,params){
var requestParams=new Array();
requestParams=requestParams.concat(params);
det.sendRequest({method:"POST",serverUrl:Workspace.serverContext+"/action/"+actionType,action:actionType,parameters:requestParams,callingController:this});}
FitRatingController.prototype.catchEvent=function(eventKey,attributes){
if(this.isEnabled){if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED){
if(attributes!=undefined&&attributes.response!=undefined&&attributes["action"]=="getDetails"&&attributes.callingController==this){
if(attributes.response["errorCode"]!=undefined){this.errorCode=attributes.response["errorCode"];}
if(attributes.response["garmentDetails"]!=undefined){this.setData(attributes.response["garmentDetails"]);}else{this.setData(new Array());}}
}else if(eventKey==Workspace.events.EVENT_ONMYMODEL_ITEM_SELECTED){this.getItemRating(Model.content.selectedItemId);
}else if(eventKey==Workspace.events.EVENT_FIT_ATTRIBUTES_CHANGED){this.getRating();}}}
FitRatingController.prototype.onLoading=function(){
ParserUtils.setContainerHtml(this.containerElementId,resource.get("Fit.Rating.Loading"));}
FitRatingController.prototype.generate=function(fitRating){
ParserUtils.applyTemplate(this.templateElementId,this.containerElementId);}
FitRatingController.prototype.enable=function(){
this.isEnabled=true;this.getRating();}
FitRatingController.prototype.disable=function(){
this.isEnabled=false;}
function HelpController(id){jsClass.extend(this,[QuestionnaireController]);
this.id=id;}
HelpController.prototype.id="HelpController";HelpController.prototype.isGenerated=false;HelpController.prototype.handlerUrl="";
HelpController.prototype.init=function(){
this.super_QuestionnaireController_init();
this.handlerUrl=Workspace.serverContext+"/action/";}
HelpController.prototype.show=function(){
if(!this.isGenerated){
this.isGenerated=true;
ParserUtils.applyTemplate(this.id+"Template",this.id+"Container");
this.initFields(this.defaultAnswersMap);}}
HelpController.prototype.hide=function(){
Anim.reset(this.id+"Panel");}
HelpController.prototype.showTechnicalSupport=function(){
Anim.openSingle(this.id+"TechnicalSupportPanel");}
HelpController.prototype.sendTechnicalSupport=function(){
if(this.isAllFieldsValid()){
this.sendRequest("helpSubmit",this.getTechnicalSupportParameters());Anim.reset(this.id+"TechnicalSupportPanel");
}else{
this.updateFields();var foundInvalidField=false;}}
HelpController.prototype.getTechnicalSupportParameters=function(){
var parserAttributes={keyValueSeparator:"=",pairSeparator:"\n",arrayOpeningSeparator:"\n",arrayClosingSeparator:"\n",mapOpeningSeparator:"\n",mapClosingSeparator:"\n",stringOpeningSeparator:"",stringClosingSeparator:"",isShowArrayIndex:true,isIndentByLevel:true,isParseControllers:false,maxRecursionLevel:3}
var stateInfo=new Array();stateInfo["productVersion"]=typeof(version)!="undefined"?version : "indev";stateInfo["query"]=Workspace.query;stateInfo["navigator"]=navigator;stateInfo["userAgent"]=navigator.userAgent;stateInfo["user"]=Workspace.user;stateInfo["screen"]=window.screen.width+"x"+window.screen.height+" "+window.screen.colorDepth+"bits";stateInfo["cookies"]=CookieUtils.data;
var params=new Array();params[params.length]=["email",this.fieldObjectMap["HelpSenderEmail"].getValue()];params[params.length]=["body",this.fieldObjectMap["HelpMessage"].getValue()+"\n\r\n\r--------------------------------------------------------\n\rSession information:\n\r"+ParserUtils.serializeObject(stateInfo,parserAttributes)];
return params;}
HelpController.prototype.sendRequest=function(action,params){
det.sendRequest({serverUrl:this.handlerUrl+action,action:action,parameters:params,callingController:this});}
HelpController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED&&attributes.callingController==this){
if(attributes.action=="helpSubmit"&&attributes.response!=undefined&&attributes.response["errorCode"]==undefined){Workspace.message.displayMessage(resource.get("HelpTechnicalSupport.confirmation"));}
}}
function HistoryController(id){
this.id=id;}
HistoryController.prototype.id="HistoryController";HistoryController.prototype.itemList=undefined;HistoryController.prototype.isInitialized=false;HistoryController.prototype.isGenerated=false;HistoryController.prototype.maxCount=20;HistoryController.prototype.handlerUrl=undefined;HistoryController.prototype.selectedItemId=undefined;HistoryController.prototype.lastSelectedItemId=undefined;
HistoryController.prototype.init=function(){
this.handlerUrl=Workspace.serverContext+"/action/catalog";this.itemList=new Array();
var cookieItemList=CookieUtils.getAttribute(this.id+"list");
if(cookieItemList!=undefined){
this.itemList=new Array(cookieItemList.split("|"))[0];log.debug("Loaded "+this.id+" item history from session cookie:" +cookieItemList,this);}
this.isInitialized=true;}
HistoryController.prototype.show=function(){
if(!this.isGenerated){this.selectItem(0);this.isGenerated=true;Items.loadItemInfo(this.itemList,this.id+".generate()");}}
HistoryController.prototype.selectItem=function(index){
if(index<this.itemList.length){this.selectedItemId=this.itemList[index];
if(this.selectedItemId!=this.lastSelectedItemId){this.generate();Workspace.events.throwEvent(Workspace.events.EVENT_ONMYMODEL_ITEM_SELECTED,this);}
this.lastSelectedItemId=this.selectedItemId;}}
HistoryController.prototype.hide=function(){}
HistoryController.prototype.generate=function(){
ParserUtils.applyTemplate(this.id+"Template",this.id+"Container",this);}
HistoryController.prototype.add=function(key,itemInfo){
for(index in this.itemList){if(this.itemList[index]==key){
if(parseInt(index)==0){this.itemList=this.itemList.slice(1,this.itemList.length);}else if(parseInt(index)==this.itemList.length-1){this.itemList=this.itemList.slice(0,this.itemList.length-1);}else{this.itemList=this.itemList.slice(0,index).concat(this.itemList.slice(parseInt(index)+1,this.itemList.length));}
break;}}
var newItemArray=new Array();newItemArray.push(key);
this.itemList=newItemArray.concat(this.itemList);
if(this.itemList.length>this.maxCount){this.itemList=this.itemList.slice(0,this.maxCount-1);}
this.selectItem(0);
CookieUtils.setAttribute(this.id+"list",this.itemList.join("|"),true);}
function RemovedItemHistoryController(id){jsClass.extend(this,[HistoryController]);
this.id=id;}
RemovedItemHistoryController.prototype.previousItemsList=undefined;
RemovedItemHistoryController.prototype.init=function(){
this.super_HistoryController_init();
this.previousItemsList=Model.content.allItemsArray;
Workspace.events.addListener(Workspace.events.EVENT_MODEL_CONTENT_CHANGED,this);}
RemovedItemHistoryController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_MODEL_CONTENT_CHANGED&&attributes!=undefined){
var currentItemsMap=MapUtils.toMap(attributes.onMyModelArray["allItemsIds"]);var previousItemsList=(this.previousItemsList!=undefined?this.previousItemsList : new Array());var lastAffectedItemId=this.getModelLastItemIdAffected();var itemId=undefined;var itemInfo=undefined;var categoryInfo=undefined;
var requestedItemInfoList=new Array();
for(var i=0;i<previousItemsList.length;i++){
var itemId=previousItemsList[i];
try{
if(currentItemsMap[itemId]==undefined&&Items.getItemFromItemId(itemId)["CATEGORIES"].length>0){this.add(itemId);}}catch(e){log.debug("Could not add itemId:"+itemId+" to history("+e.message()+")",this);}}
this.previousItemsList=new Array(attributes.onMyModelArray["allItemsIds"])[0];this.generate();}}
RemovedItemHistoryController.prototype.getModelLastItemIdAffected=function(){
var affectedItemId=undefined;var map=new Array();var modelLastActionParameters=Model.lastActionParameters;
if(modelLastActionParameters!=undefined){
var garmentId=modelLastActionParameters["garmentsID"];
if(garmentId!=undefined){var itemInfo=Items.getItemFromGarmentId(garmentId);
if(itemInfo!=undefined){affectedItemId=itemInfo["ID_ITEM"];}}}
return affectedItemId;}
RemovedItemHistoryController.prototype.add=function(key){
Workspace.events.throwEvent(
Workspace.events.EVENT_REMOVED_HISTORY_ADDED,
this);
this.super_HistoryController_add(key);}
function ItemCacheController(id){
this.id=id;}
ItemCacheController.prototype.id="ItemCacheController";ItemCacheController.prototype.itemMap=undefined;ItemCacheController.prototype.garmentMap=undefined;ItemCacheController.prototype.onCompleteArray=undefined;
ItemCacheController.prototype.init=function(){
Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);
this.itemMap=new Array();this.garmentMap=new Array();
Workspace.events.throwEvent(Workspace.events.EVENT_CONTROLLER_INITIALIZED,this);
if(Workspace.viewData!=undefined){if(Workspace.viewData["itemsInfo"]!=undefined){this.addItemBatchGarments(Workspace.viewData["itemsInfo"]);}}}
ItemCacheController.prototype.set=function(itemId,itemInfo){
if(itemId!=undefined&&itemId!=""&&itemInfo!=undefined){
itemId=itemId+"";
if(itemInfo["GARMENTS"]!=undefined){for(garmentIndex in itemInfo["GARMENTS"]){this.garmentMap[itemInfo["GARMENTS"][garmentIndex]["ID_GARMENT"]]=itemInfo;}}
this.itemMap[itemId]=itemInfo;;}}
ItemCacheController.prototype.addItemBatch=function(itemList,onComplete){
for(var key in itemList){this.set(key,itemList[key]);}
if(onComplete!=undefined){eval(onComplete);}}
ItemCacheController.prototype.addItemBatchGarments=function(garmentsList,onComplete){
for(var key in garmentsList){
var itemId=garmentsList[key]["ID_ITEM"];this.set(itemId,garmentsList[key]);}
if(onComplete!=undefined){eval(onComplete);}}
ItemCacheController.prototype.getItemFromItemId=function(itemId){
itemId=itemId+"";
return this.itemMap[itemId];}
ItemCacheController.prototype.getItemId=function(garmentId){
garmentId=garmentId+"";
if(garmentId!=undefined&&garmentId!=""){
if(garmentId.indexOf(":")>-1){garmentId=garmentId.match(/(.*)\:/)[1];}
var item=this.garmentMap[garmentId];
if(item!=undefined&&item["ID_ITEM"]!=undefined){return item["ID_ITEM"];}else{return undefined;}}else{return undefined;}}
ItemCacheController.prototype.getItemFromGarmentId=function(garmentId){
if(garmentId==undefined){return undefined;}else{return this.garmentMap[garmentId.split(":")[0]];}
}
ItemCacheController.prototype.getItemsArray=function(itemIdList){
var resultArray=new Array();
for(var index in itemIdList){resultArray.push(this.getItemFromItemId(itemIdList[index]));}
return resultArray;}
ItemCacheController.prototype.loadItemInfo=function(itemIdList,onComplete){
if(itemIdList!=undefined){
var requestedItemIds=new Array();
for(var index in itemIdList){if(this.itemMap[itemIdList[index]]==undefined){requestedItemIds.push(itemIdList[index]);}}
if(requestedItemIds.length>0&&requestedItemIds.join(",")!=""){this.sendRequest("getItemsInfo",[["itemIds",requestedItemIds.join(",")]],onComplete);}else if(onComplete!=undefined){eval(onComplete);}}}
ItemCacheController.prototype.loadItemInfoFromGarments=function(garmentIdList,onComplete){
if(garmentIdList!=undefined){
var requestedGarmentIds=new Array();
for(var index in garmentIdList){if(this.garmentMap[garmentIdList[index]]==undefined){requestedGarmentIds.push(garmentIdList[index]);}}
if(requestedGarmentIds.length>0){this.sendRequest("getItemsInfo",[["garmentIds",requestedGarmentIds.join(",")]],onComplete);}else if(onComplete!=undefined){eval(onComplete);}}
}
ItemCacheController.prototype.loadItemGroupingInfos=function(itemIdList,onComplete){
var allItemsGrouping=new Array();var itemGroupingInfo=undefined;
for(var index in itemIdList){
itemGroupingInfo=this.getItemFromItemId(itemIdList[index])["ITEM_GROUPING"];
if(this.itemMap[itemIdList[index]]!=undefined&&itemGroupingInfo!=undefined){allItemsGrouping=allItemsGrouping.concat(itemGroupingInfo);}}
if(allItemsGrouping!=undefined){this.loadItemInfo(allItemsGrouping,onComplete);}else{eval(onComplete);}}
ItemCacheController.prototype.loadGreatGoTogetherItems=function(itemId,onComplete){
var item=this.itemMap[itemId];
if(item!=undefined&&item["GOTOGETHERS"]!=undefined){this.loadItemInfo(item["GOTOGETHERS"][0]["ITEMS"],onComplete);}else if(onComplete!=undefined){eval(onComplete);}}
ItemCacheController.prototype.callProductPage=function(itemId){var item=Items.getItemFromItemId(itemId);
if(item!=undefined){
var params=new Array();
params[params.length]=["params","il:"+itemId];params[params.length]=["eventKey","Buy"];
this.sendRequest("logEvent",params,Workspace.serverContext+"/action/logEvent");
Workspace.events.throwEvent(Workspace.events.EVENT_PRODUCT_PAGE_CALL,item);
Workspace.callUrlInParent(decodeURIComponent(item["PRODUCT_PAGE_URL"]));}}
ItemCacheController.prototype.sendRequest=function(actionType,params,onComplete){
var requestParams=new Array();
requestParams=requestParams.concat(params);
this.onLoadComplete=onComplete;
det.sendRequest({serverUrl:Workspace.serverContext+"/action/"+actionType,action:actionType,parameters:requestParams,callingController:this,info:onComplete});}
ItemCacheController.prototype.isAvailable=function(itemId){
var returnValue=false
var item=this.itemMap[itemId];
if(item!=undefined){
for(var index in item["GARMENTS"]){if(item["GARMENTS"][index]["AVAILABILITY"]=="1"){returnValue=true;break;}}}
return returnValue;}
ItemCacheController.prototype.isCompatible=function(itemId){
var returnValue=true;
if(typeof(Model)!="undefined"&&this.itemMap[itemId]!=undefined&&this.itemMap[itemId]["BODYSETS"]!=undefined&&this.itemMap[itemId]["BODYSETS"].length>0){returnValue=Model.isBodySetMatched(this.itemMap[itemId]["BODYSETS"]);}
return returnValue;}
ItemCacheController.prototype.isFallback=function(itemId){
var returnValue=false;if(this.itemMap[itemId]!=undefined&&this.itemMap[itemId]["TYPE_ITEMS"]=="F"){returnValue=true;}
return returnValue;}
ItemCacheController.prototype.isOutfit=function(itemId){
var item=this.itemMap[itemId];if(item!=undefined&&item["GROUP_ID"]=="998"){return true;}else{return false;}}
ItemCacheController.prototype.isSet=function(itemId){
var item=this.itemMap[itemId];if(item!=undefined&&item["GROUP_ID"]=="999"){return true;}else{return false;}}
ItemCacheController.prototype.getFirstAvailableGarment=function(itemId){
var returnValue=undefined;var item=this.itemMap[itemId];
if(item!=undefined){
for(var index in item["GARMENTS"]){if(item["GARMENTS"][index]["AVAILABILITY"]=="1"){returnValue=item["GARMENTS"][index]["ID_GARMENT"];break;}}}
return returnValue;}
ItemCacheController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED&&attributes.response!=undefined){
if(attributes.callingController==this&&attributes.action=="getItemsInfo"){
if(attributes.parametersMap["garmentIds"]!=undefined){this.addItemBatchGarments(attributes.response,attributes.info);}else{this.addItemBatch(attributes.response,attributes.info);}
}else if(attributes.response["itemsInfo"]!=undefined){this.addItemBatch(attributes.response["itemsInfo"]);}}}
function ColorAdjustController(id){
this.id=id;return this;}
ColorAdjustController.prototype.id="ColorAdjustController";ColorAdjustController.prototype.isGenerated=false;ColorAdjustController.prototype.loadedImages=undefined;ColorAdjustController.prototype.headImageAttributes=undefined;ColorAdjustController.prototype.selectedColorCorrectionIndex=0;
ColorAdjustController.prototype.suggestionList=[{"colorshift":{"r":"-10","b":"0","g":"0","pCent":"true"}},{"colorshift":{"r":"-10","b":"-10","g":"0","pCent":"true"}},{"colorshift":{"r":"0","b":"-10","g":"0","pCent":"true"}},{"colorshift":{"r":"0","b":"0","g":"0","pCent":"true"}},{"colorshift":{"r":"0","b":"-10","g":"-10","pCent":"true"}},{"colorshift":{"r":"0","b":"0","g":"-10","pCent":"true"}},{"colorshift":{"r":"-10","b":"0","g":"-10","pCent":"true"}}
];
ColorAdjustController.prototype.init=function(){
resource.applyProperties(this.id+"Properties",this);}
ColorAdjustController.prototype.generate=function(){
if(!this.parameters["isBackAction"]){ParserUtils.applyTemplate(this.id+"Template",this.id+"Container",this,this.id+".isGenerated=true;Workspace.hideWait();");}else{Workspace.hideWait();}}
ColorAdjustController.prototype.show=function(){
this.generate();}
ColorAdjustController.prototype.updateBackgroundModelImage=function(){
var modelBackgroundElement=document.getElementById(this.id+"ModelBackground");
if(modelBackgroundElement!=undefined){document.getElementById(this.id+"ModelBackground").src=document.getElementById("FaceMapping_ModelImage").src;}}
ColorAdjustController.prototype.select=function(index){
this.selectedColorCorrectionIndex=index;}
ColorAdjustController.prototype.getParameters=function(){
var parameters=new Array();parameters["transformationsList"]=new Array();parameters["transformationsList"].push(this.suggestionList[this.selectedColorCorrectionIndex]);
return parameters;}
ColorAdjustController.prototype.setParameters=function(parameters,isForcedUpdate){
isForcedUpdate=isForcedUpdate==undefined?false : true;
this.parameters=MapUtils.putAll(this.parameters,parameters);
this.headImageAttributes=new Array();this.headImageAttributes["left"]=this.parameters["metaData"]["positionX"];this.headImageAttributes["top"]=this.parameters["metaData"]["positionY"];
for(var i in this.parameters["transformationsList"]){
if(this.parameters["transformationsList"][i]["resize"]!=undefined){this.headImageAttributes["width"]=this.parameters["transformationsList"][i]["resize"]["w"];this.headImageAttributes["height"]=this.parameters["transformationsList"][i]["resize"]["h"];break;}}
if(isForcedUpdate){this.generate();}}
function ColorShiftController(id){
this.id=id;return this;}
ColorShiftController.prototype.isGenerated=false;ColorShiftController.prototype.initialParameters=undefined;ColorShiftController.prototype.bodyImage=undefined;ColorShiftController.prototype.imageHeight=800;ColorShiftController.prototype.imageWidth=358;ColorShiftController.prototype.arrayControls=undefined;ColorShiftController.prototype.id="ColorShiftController";ColorShiftController.prototype.parameters={"red":0,"green":0,"blue":0,"brightness":0};ColorShiftController.prototype.isIE6=false;
ColorShiftController.prototype.isRedImageLoaded=false;ColorShiftController.prototype.isGreenImageLoaded=false;ColorShiftController.prototype.isBlueImageLoaded=false;ColorShiftController.prototype.isWhiteImageLoaded=false;ColorShiftController.prototype.isBlackImageLoaded=false;
ColorShiftController.prototype.init=function(){
this.arrayControls=new Array();resource.applyProperties(this.id+"Properties",this);}
ColorShiftController.prototype.initSkinElement=function(){
if(navigator.userAgent.indexOf("MSIE 6.0")>-1){this.isIE6=true;}
this.initSliders();
this.getChannels();
loopUntil("ColorShift.isAllChannelsLoaded()",escape("Workspace.hideWait();"+this.id+".updateImage("+parseInt(this.arrayControls[0].value)+","+parseInt(this.arrayControls[1].value)+","+parseInt(this.arrayControls[2].value)+","+parseInt(this.arrayControls[3].value)+")"));
this.updateBackgroundModelImage();
var imgBody=new Image();imgBody.src=document.getElementById("colorShiftModelImage").src;
this.bodyImage=imgBody;
this.parameters["metaData"]["positionX"]+=parseInt(document.getElementById("colorShiftModelImage").style.left);this.parameters["metaData"]["positionY"]+=parseInt(document.getElementById("colorShiftModelImage").style.top);}
ColorShiftController.prototype.updateBackgroundModelImage=function(){
if(document.getElementById("colorShiftModelImage")==undefined){loopUntil("document.getElementById('colorShiftModelImage')!=undefined",this.id+".updateBackgroundModelImage()");}else{document.getElementById("colorShiftModelImage").src=document.getElementById("FaceMapping_ModelImage").src;}}
ColorShiftController.prototype.getChannels=function(){
ColorShift.isRedImageLoaded=false;ColorShift.isGreenImageLoaded=false;ColorShift.isBlueImageLoaded=false;ColorShift.isWhiteImageLoaded=false;ColorShift.isBlackImageLoaded=false;
Media.loadImage(
this.parameters["mediaId"],Media.serializeTransformations(this.parameters["transformationsList"].concat([{"colorshift":{"r":0,"g":-100,"b":-100,"pCent":true}}])),undefined,"colorShiftImageRed");
Media.loadImage(
this.parameters["mediaId"],Media.serializeTransformations(this.parameters["transformationsList"].concat([{"colorshift":{"r":-100,"g":-100,"b":0,"pCent":true}}])),undefined,"colorShiftImageBlue");
Media.loadImage(
this.parameters["mediaId"],Media.serializeTransformations(this.parameters["transformationsList"].concat([{"colorshift":{"r":-100,"g":0,"b":-100,"pCent":true}}])),undefined,"colorShiftImageGreen");
Media.loadImage(
this.parameters["mediaId"],Media.serializeTransformations(this.parameters["transformationsList"].concat([{"colorshift":{"r":-100,"g":-100,"b":-100,"pCent":true}}])),undefined,"colorShiftImageBlack");
Media.loadImage(
this.parameters["mediaId"],Media.serializeTransformations(this.parameters["transformationsList"].concat([{"colorshift":{"r":255,"g":255,"b":255,"pCent":false}}])),undefined,"colorShiftImageWhite");}
ColorShiftController.prototype.initSliders=function(){
this.arrayControls[0]=new FieldObjectSlider(this.id+".arrayControls[0]","colorShiftSliderRed");this.arrayControls[1]=new FieldObjectSlider(this.id+".arrayControls[1]","colorShiftSliderGreen");this.arrayControls[2]=new FieldObjectSlider(this.id+".arrayControls[2]","colorShiftSliderBlue");this.arrayControls[3]=new FieldObjectSlider(this.id+".arrayControls[3]","colorShiftSliderBrightness");
this.arrayControls[0].init();this.arrayControls[1].init();this.arrayControls[2].init();this.arrayControls[3].init();
this.updateUserInterface(this.parameters);}
ColorShiftController.prototype.generate=function(){
if(!this.isGenerated){ParserUtils.applyTemplate(this.id+"Template",this.id+"Container",this,this.id+".initSkinElement();"+this.id+".isGenerated=true;");}else{
if(!this.parameters["isBackAction"]){
this.getChannels();loopUntil("ColorShift.isAllChannelsLoaded()",escape("Workspace.hideWait();"+this.id+".updateImage("+parseInt(this.arrayControls[0].value)+","+parseInt(this.arrayControls[1].value)+","+parseInt(this.arrayControls[2].value)+","+parseInt(this.arrayControls[3].value)+")"));}else{Workspace.hideWait();}}}
ColorShiftController.prototype.reset=function(){
this.parameters["red"]=0;this.parameters["green"]=0;this.parameters["blue"]=0;this.parameters["brightness"]=0;
this.initSliders();}
ColorShiftController.prototype.isAllChannelsLoaded=function(){
if(this.isRedImageLoaded==true&&
this.isGreenImageLoaded==true&&
this.isBlueImageLoaded==true&&
this.isWhiteImageLoaded==true&&
this.isBlackImageLoaded==true){
return true;}
else{return false;}}
ColorShiftController.prototype.updateUserInterface=function(parameters){
this.arrayControls[0].setValue(parseInt(parameters["red"]),true);this.arrayControls[1].setValue(parseInt(parameters["green"]),true);this.arrayControls[2].setValue(parseInt(parameters["blue"]),true);this.arrayControls[3].setValue(parseInt(parameters["brightness"]),true);
if(this.isIE6){eval(this.arrayControls[0].onDropFunc);eval(this.arrayControls[1].onDropFunc);eval(this.arrayControls[2].onDropFunc);eval(this.arrayControls[3].onDropFunc);}else{
eval(this.arrayControls[0].onDragFunc);eval(this.arrayControls[1].onDragFunc);eval(this.arrayControls[2].onDragFunc);eval(this.arrayControls[3].onDragFunc);}
}
ColorShiftController.prototype.getParameters=function(){
var parameters=new Array();var rgbShift=new Array();
var scaleValues=1.1;var brightValue=0;
if(this.parameters["brightness"]<0){brightValue=(this.parameters["brightness"]);}else{brightValue=(this.parameters["brightness"] * 4);}
var redValue=parseInt((this.parameters["red"] * 100-100)* scaleValues);var greenValue=parseInt((this.parameters["green"] * 100-100)* scaleValues);var blueValue=parseInt((this.parameters["blue"] * 100-100)* scaleValues);
rgbShift={"colorshift":{"r":redValue,"g":greenValue,"b":blueValue,"pCent":false}};
brightnessShift={"colorshift":{"r":brightValue,"g":brightValue,"b":brightValue,"pCent":false}};
parameters["transformationsList"]=new Array();parameters["transformationsList"][parameters["transformationsList"].length]=rgbShift;parameters["transformationsList"][parameters["transformationsList"].length]=brightnessShift;
return parameters;}
ColorShiftController.prototype.setParameters=function(parameters,isForcedUpdate){
isForcedUpdate=isForcedUpdate==undefined?false : true;
this.parameters=MapUtils.putAll(this.parameters,parameters);
if(isForcedUpdate){this.updateUserInterface(this.parameters);}}
ColorShiftController.prototype.show=function(){
this.generate();}
ColorShiftController.prototype.isCanvasSuported=function(){
if(document.getElementById('colorShiftCanevas').getContext){return true;}else{return false;}}
ColorShiftController.prototype.updateImage=function(red,green,blue,brightness){
this.adjustColorRatio(parseFloat(red),parseFloat(green),parseFloat(blue),parseFloat(brightness));
if(this.isAllChannelsLoaded()){if(this.isCanvasSuported()){document.getElementById("dxDivBody").style.visibility="hidden";this.updateWithCanvas(this.parameters["red"],this.parameters["green"],this.parameters["blue"],brightness);}else{if(this.isIE6){this.updateWithDirectX_IE6(this.parameters["red"],this.parameters["green"],this.parameters["blue"],brightness);}else{this.updateWithDirectX(this.parameters["red"],this.parameters["green"],this.parameters["blue"],brightness);}}}}
ColorShiftController.prototype.adjustColorRatio=function(red,green,blue,brightness){
var ratios=new Array();
ratios["red"]=1;ratios["green"]=1;ratios["blue"]=1;
var realRed=red+100;var realGreen=green+100;var realBlue=blue+100;
var redValue=parseFloat(realRed);var greenValue=parseFloat(realGreen);var blueValue=parseFloat(realBlue);
var percentRed=redValue /(redValue+greenValue+blueValue);var percentGreen=greenValue /(redValue+greenValue+blueValue);var percentBlue=blueValue /(redValue+greenValue+blueValue);
var completionRatio=1.0 / Math.max(percentGreen,percentRed,percentBlue);
ratios["red"]=percentRed * completionRatio;ratios["green"]=percentGreen * completionRatio;ratios["blue"]=percentBlue * completionRatio;ratios["brightness"]=brightness;
this.parameters["red"]=ratios["red"];this.parameters["green"]=ratios["green"];this.parameters["blue"]=ratios["blue"];this.parameters["brightness"]=ratios["brightness"];}
ColorShiftController.prototype.updateWithDirectX=function(red,green,blue,brightness){
var divMask=document.getElementById("dxDivMask");
var divA=document.getElementById("dxDivA");var divB=document.getElementById("dxDivB");var divC=document.getElementById("dxDivC");var divMask=document.getElementById("dxDivMask");var divHead=document.getElementById("dxDivHead");var divWhite=document.getElementById("dxDivWhite");
var faceImageWidth=this.parameters["transformationsList"][0]["resize"]["w"];var faceImageHeight=this.parameters["transformationsList"][0]["resize"]["h"];
divA.style.width=faceImageWidth+"px";divA.style.height=faceImageHeight+"px";
divB.style.width=faceImageWidth+"px";divB.style.height=faceImageHeight+"px";
divC.style.width=faceImageWidth+"px";divC.style.height=faceImageHeight+"px";
divMask.style.width=faceImageWidth+"px";divMask.style.height=faceImageHeight+"px";
divWhite.style.width=faceImageWidth+"px";divWhite.style.height=faceImageHeight+"px";
var imgR=document.getElementById("colorShiftImageRed");var imgG=document.getElementById("colorShiftImageGreen");var imgB=document.getElementById("colorShiftImageBlue");var imgBlack=document.getElementById("colorShiftImageBlack");var imgWhite=document.getElementById("colorShiftImageWhite");
divHead.style.left=this.parameters["metaData"]["positionX"]+"px";divHead.style.top=this.parameters["metaData"]["positionY"]+"px";
divHead.style.height=faceImageHeight+"px";divHead.style.width=faceImageWidth+"px";
imgR.style.visibility="visible";imgG.style.visibility="visible";imgB.style.visibility="visible";imgBlack.style.visibility="visible";imgWhite.style.visibility="visible";
imgR.style.filter="alpha(opacity="+Math.round(this.parameters["red"] * 100.0)+")";imgG.style.filter="alpha(opacity="+Math.round(this.parameters["green"] * 100.0)+")";imgB.style.filter="alpha(opacity="+Math.round(this.parameters["blue"] * 100.0)+")";
if(this.parameters["brightness"]<0){divHead.style.filter="progid:DXImageTransform.Microsoft.Compositor(function=24)";}
else{divHead.style.filter="progid:DXImageTransform.Microsoft.Compositor(function=25)";}
imgWhite.style.filter="alpha(opacity="+Math.abs(this.parameters["brightness"])+")";
divB.style.visibility="hidden";divWhite.style.visibility="hidden";divC.style.visibility="visible";divA.style.zIndex=0;
divC.style.backgroundImage="url("+imgBlack.src+")";divB.style.backgroundImage="url("+imgBlack.src+")";divWhite.style.backgroundImage="url("+imgBlack.src+")";
divC.innerHTML=imgR.outerHTML;
divA.filters.item(0).apply();
divC.style.visibility="hidden";divMask.style.visibility="hidden";divB.style.visibility="visible";
divB.innerHTML=imgG.outerHTML;
divB.filters.item(0).apply();
divB.innerHTML=imgB.outerHTML;
divB.filters.item(0).play();divA.filters.item(0).play();
divWhite.innerHTML=imgWhite.outerHTML;divWhite.style.visibility="visible";
divHead.filters.item(0).apply();
divWhite.style.visibility="hidden";
divHead.filters.item(0).play();
imgR.style.visibility="hidden";imgG.style.visibility="hidden";imgB.style.visibility="hidden";imgBlack.visibility="hidden";imgWhite.visibility="hidden";}
ColorShiftController.prototype.updateWithDirectX_IE6=function(red,green,blue,brightness){
var divMask=document.getElementById("dxDivMask");
var divA=document.getElementById("dxDivA");var divB=document.getElementById("dxDivB");var divC=document.getElementById("dxDivC");var divMask=document.getElementById("dxDivMask");var divMask2=document.getElementById("dxDivMask2");var divHead=document.getElementById("dxDivHead");var divWhite=document.getElementById("dxDivWhite");
var faceImageWidth=this.parameters["transformationsList"][0]["resize"]["w"];var faceImageHeight=this.parameters["transformationsList"][0]["resize"]["h"];
divA.style.width=faceImageWidth+"px";divA.style.height=faceImageHeight+"px";
divB.style.width=faceImageWidth+"px";divB.style.height=faceImageHeight+"px";
divC.style.width=faceImageWidth+"px";divC.style.height=faceImageHeight+"px";
divMask.style.width=faceImageWidth+"px";divMask.style.height=faceImageHeight+"px";
divMask2.style.width=faceImageWidth+"px";divMask2.style.height=faceImageHeight+"px";
divWhite.style.width=faceImageWidth+"px";divWhite.style.height=faceImageHeight+"px";
var imgR=document.getElementById("colorShiftImageRed");var imgG=document.getElementById("colorShiftImageGreen");var imgB=document.getElementById("colorShiftImageBlue");var imgBlack=document.getElementById("colorShiftImageBlack");var imgWhite=document.getElementById("colorShiftImageWhite");
divHead.style.left=this.parameters["metaData"]["positionX"]+"px";divHead.style.top=this.parameters["metaData"]["positionY"]+"px";divHead.style.width=faceImageWidth+"px";divHead.style.height=faceImageHeight+"px";
imgR.style.visibility="visible";imgG.style.visibility="visible";imgB.style.visibility="visible";imgBlack.style.visibility="visible";imgWhite.style.visibility="visible";
if(this.parameters["brightness"]>=0){
imgR.style.filter="alpha(opacity="+Math.round(this.parameters["red"] * 100.0)+")progid:DXImageTransform.Microsoft.AlphaImageLoader();";imgG.style.filter="alpha(opacity="+Math.round(this.parameters["green"] * 100.0)+")progid:DXImageTransform.Microsoft.AlphaImageLoader();";imgB.style.filter="alpha(opacity="+Math.round(this.parameters["blue"] * 100.0)+")progid:DXImageTransform.Microsoft.AlphaImageLoader();";imgWhite.style.filter="alpha(opacity="+Math.abs(this.parameters["brightness"])+")progid:DXImageTransform.Microsoft.AlphaImageLoader();";}else{
imgR.style.filter="alpha(opacity="+Math.round((this.parameters["red"] * 100.0)+this.parameters["brightness"])+")progid:DXImageTransform.Microsoft.AlphaImageLoader();";imgG.style.filter="alpha(opacity="+Math.round((this.parameters["green"] * 100.0)+this.parameters["brightness"])+")progid:DXImageTransform.Microsoft.AlphaImageLoader();";imgB.style.filter="alpha(opacity="+Math.round((this.parameters["blue"] * 100.0)+this.parameters["brightness"])+")progid:DXImageTransform.Microsoft.AlphaImageLoader();";imgWhite.style.filter="alpha(opacity=0)progid:DXImageTransform.Microsoft.AlphaImageLoader();";}
divA.style.visibility="visible";divB.style.visibility="hidden";divWhite.style.visibility="hidden";divMask2.style.visibility="hidden";divMask.style.visibility="visible";divC.style.visibility="visible";
divMask2.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src=imgBlack.src;divMask.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src=imgBlack.src;
divC.innerHTML=imgR.outerHTML;divC.children[0].filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src=imgR.src;divC.children[0].src="/images/spacer.gif"
divC.zIndex=0;
divA.filters.item("DXImageTransform.Microsoft.Compositor").apply();
divC.style.visibility="hidden";divMask.style.visibility="hidden";divB.style.visibility="visible";
divB.innerHTML="<div style='position:absolute;top:0px;left:0px;height:"+faceImageHeight+"px;width:"+faceImageWidth+"px;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=\"image\")'></div>"+imgG.outerHTML;divB.children[0].filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src= imgBlack.src;divB.children[1].filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src=imgG.src;divB.children[1].src="/images/spacer.gif"
divB.zIndex=0;
divB.filters.item("DXImageTransform.Microsoft.Compositor").apply();
divB.innerHTML="<div style='position:absolute;top:0px;left:0px;height:"+faceImageHeight+"px;width:"+faceImageWidth+"px;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=\"image\")'></div>"+imgB.outerHTML;divB.children[0].filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src= imgBlack.src;divB.children[1].filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src=imgB.src;divB.children[1].src="/images/spacer.gif"
divB.filters.item("DXImageTransform.Microsoft.Compositor").play();divA.filters.item("DXImageTransform.Microsoft.Compositor").play();divHead.filters.item("DXImageTransform.Microsoft.Compositor").apply();
divA.style.visibility="hidden";divMask2.style.visibility="visible";divWhite.style.visibility="visible";
divWhite.innerHTML=imgWhite.outerHTML;divWhite.children[0].filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src=imgWhite.src;divWhite.children[0].src="/images/spacer.gif";
divHead.filters.item("DXImageTransform.Microsoft.Compositor").play();
imgR.style.visibility="hidden";imgG.style.visibility="hidden";imgB.style.visibility="hidden";imgBlack.visibility="hidden";imgWhite.visibility="hidden";}
ColorShiftController.prototype.updateWithCanvas=function(red,green,blue,brightness){
var ctx=document.getElementById('colorShiftCanevas').getContext('2d');
var imgR=document.getElementById("colorShiftImageRed");var imgG=document.getElementById("colorShiftImageGreen");var imgB=document.getElementById("colorShiftImageBlue");var imgBlack=document.getElementById("colorShiftImageBlack");var imgWhite=document.getElementById("colorShiftImageWhite");var imgBody=document.getElementById("colorShiftModelImage");
ctx.globalAlpha=1.0;ctx.globalCompositeOperation='source-over';ctx.drawImage(imgBody,0,80);
ctx.drawImage(imgBlack,this.parameters["metaData"]["positionX"],this.parameters["metaData"]["positionY"]);
var minusBrightness=100.0;
if(this.parameters["brightness"]<0){minusBrightness=this.parameters["brightness"]+100.0;}
ctx.globalCompositeOperation='lighter';RedImage=new Image();RedImage.src=imgR.src;
ctx.globalAlpha=(Math.round(this.parameters["red"] * minusBrightness)/ 100.0);ctx.drawImage(RedImage,this.parameters["metaData"]["positionX"],this.parameters["metaData"]["positionY"]);ctx.globalAlpha=1.0;
GreenImage=new Image();GreenImage.src=imgG.src;
ctx.globalAlpha=(Math.round(this.parameters["green"] * minusBrightness)/ 100.0);ctx.drawImage(GreenImage,this.parameters["metaData"]["positionX"],this.parameters["metaData"]["positionY"]);ctx.globalAlpha=1.0;
BlueImage=new Image();BlueImage.src=imgB.src;
ctx.globalAlpha=(Math.round(this.parameters["blue"] * minusBrightness)/ 100.0);ctx.drawImage(BlueImage,this.parameters["metaData"]["positionX"],this.parameters["metaData"]["positionY"]);ctx.globalAlpha=1.0;
WhiteImage=new Image();WhiteImage.src=imgWhite.src;
if(this.parameters["brightness"]<0){ctx.globalAlpha=(0.0);}else{ctx.globalAlpha=(Math.round(Math.abs(this.parameters["brightness"]))/ 100.0);}
ctx.drawImage(WhiteImage,this.parameters["metaData"]["positionX"],this.parameters["metaData"]["positionY"]);}
function CropController(id){
this.id=id;return this;}
CropController.prototype.isGenerated=false;CropController.prototype.mediaId=2;CropController.prototype.arrayControls=undefined;CropController.prototype.parameters={"mediaWidth":0,"mediaHeight":0,"newWidth":0,"newHeight":0,"top":0,"left":0,"X1":0,"X2":0,"Y1":0,"Y2":0};CropController.prototype.id="CropController";CropController.prototype.cornerControlId="Crop_CornerControl";CropController.prototype.controlCorrection=7;CropController.prototype.ratio=1.0;CropController.prototype.isImageLoaded=false;
CropController.prototype.init=function(){
resource.applyProperties(this.id+"Properties",this);}
CropController.prototype.show=function(){
if(!this.isGenerated){ParserUtils.applyTemplate(this.id+"Template",this.id+"Container",this,"Crop.generate();Crop.reset();Crop.isGenerated=true;");}else{if(!this.parameters["isBackAction"]){this.generate();this.updateUserInterface();}}}
CropController.prototype.generate=function(isForced){
this.getWorkingImage();this.setupDragAndDrop();this.onResize();}
CropController.prototype.setInitialParameters=function(){
var bodyDiv=document.getElementById("Crop_Body");var wholeImageDiv=document.getElementById("Crop_WholeImage");
this.parameters["newHeight"]=parseInt(bodyDiv.style.height)-this.controlCorrection;this.parameters["newWidth"]=parseInt(bodyDiv.style.width)-this.controlCorrection;this.parameters["top"]=parseInt(wholeImageDiv.style.top);this.parameters["left"]=parseInt(wholeImageDiv.style.left);}
CropController.prototype.reset=function(){
this.setInitialParameters();this.updateUserInterface();}
CropController.prototype.getWorkingImage=function(){
var cropImageLoader=document.getElementById("Crop_imageLoader");var transformationsList=new Array();var cropBody=document.getElementById("Crop_Body");this.isImageLoaded=false;
var imageHeight=0;var imageWidth=0;
if(this.parameters["mediaWidth"]>this.parameters["mediaHeight"]){imageWidth=parseInt(cropBody.style.width);this.ratio=imageWidth / this.parameters["mediaWidth"];imageHeight=this.parameters["mediaHeight"] * this.ratio;}
else{imageHeight=parseInt(cropBody.style.height);this.ratio=imageHeight / this.parameters["mediaHeight"];imageWidth=this.parameters["mediaWidth"] * this.ratio;}
transformationsList.push({"resize":{w: Math.round(imageWidth),h: Math.round(imageHeight)}});
transformationsList.push({"convert":{"fmt":"jpg"}});
var wholeImageUrl=Media.getImageUrl(
this.parameters["mediaId"],Media.serializeTransformations(this.parameters["transformationsList"].concat(transformationsList.concat())),this.parameters["cacheId"]);
if(!this.parameters["isBackAction"]){Workspace.showWait();}
cropImageLoader.src=wholeImageUrl;
loopUntil(this.id+".isImageLoaded==true",escape(this.id+".showImage();"));}
CropController.prototype.showImage=function(){
var wholeImage=document.getElementById("Crop_WholeImage");var cropImageLoader=document.getElementById("Crop_imageLoader");
wholeImage.src=cropImageLoader.src;
Workspace.hideWait();}
CropController.prototype.setupDragAndDrop=function(){
var zoneDiv=document.getElementById("Crop_ZoneDiv");var wholeImage=document.getElementById("Crop_WholeImage");
DragDrop.doDrag(zoneDiv.id,{isResetOnDrop:false,containerElementId:"Crop_Body",onDrag:"Crop.onDrag()"});
DragDrop.doDrag(this.cornerControlId,{isResetOnDrop:false,containerElementId:"Crop_Body",onDrag:"Crop.onDragCornerControl()",onDrop:"Crop.updateControlsPosition()"});
this.updateUserInterface();}
CropController.prototype.updateUserInterface=function(){
var zoneDiv=document.getElementById("Crop_ZoneDiv");
zoneDiv.style.width=this.parameters["newWidth"]+"px";zoneDiv.style.height=this.parameters["newHeight"]+"px";
zoneDiv.style.left=this.parameters["left"]+"px";zoneDiv.style.top=this.parameters["top"]+"px";
this.updateControlsPosition();}
CropController.prototype.updateControlsPosition=function(){
var zoneDiv=document.getElementById("Crop_ZoneDiv");
document.getElementById(this.cornerControlId).style.top=(parseInt(zoneDiv.style.height)+parseInt(zoneDiv.style.top)-this.controlCorrection)+"px";document.getElementById(this.cornerControlId).style.left=(parseInt(zoneDiv.style.width)+parseInt(zoneDiv.style.left)-this.controlCorrection)+"px";}
CropController.prototype.onResize=function(){
var zoneDiv=document.getElementById("Crop_ZoneDiv");
Crop.parameters["newWidth"]=parseInt(zoneDiv.style.width);Crop.parameters["newHeight"]=parseInt(zoneDiv.style.height);}
CropController.prototype.onDrag=function(){
var zoneDiv=document.getElementById("Crop_ZoneDiv");
Crop.parameters["left"]=parseInt(zoneDiv.style.left);Crop.parameters["top"]=parseInt(zoneDiv.style.top);
this.updateControlsPosition();}
CropController.prototype.onDragCornerControl=function(){
var headDiv=document.getElementById("Crop_ZoneDiv");var bodyDiv=document.getElementById("Crop_WholeImage");var cornerControl=document.getElementById(this.cornerControlId);
var newWidth=parseInt(cornerControl.style.left)-(parseInt(headDiv.style.left))+this.controlCorrection;var newHeight=parseInt(cornerControl.style.top)-(parseInt(headDiv.style.top))+this.controlCorrection;
var widthDiff=newWidth-(parseInt(headDiv.style.width));var heightDiff=newHeight-(parseInt(headDiv.style.height));
newWidth+=widthDiff;newHeight+=heightDiff;
if(newWidth<20){widthDiff=0;newWidth=20;}
if(newWidth>(parseInt(bodyDiv.style.width))){widthDiff=0;newWidth=parseInt(bodyDiv.style.width);}
if(newHeight<20){heightDiff=0;newHeight=20;}
if(newHeight>(parseInt(bodyDiv.style.height))){heightDiff=0;newHeight=parseInt(bodyDiv.style.height);}
var newTop=(parseInt(headDiv.style.top)-heightDiff);var newLeft=(parseInt(headDiv.style.left)-widthDiff);
if(newTop<0){newTop=0;}
if(newLeft<0){newLeft=0;}
if(newLeft>(parseInt(bodyDiv.style.width)+parseInt(bodyDiv.style.left)-newWidth)){newLeft=(parseInt(bodyDiv.style.width)+parseInt(bodyDiv.style.left)-newWidth);}
if(newTop>(parseInt(bodyDiv.style.top)+parseInt(bodyDiv.style.height)-newHeight)){newTop=(parseInt(bodyDiv.style.top)+parseInt(bodyDiv.style.height)-newHeight);}
headDiv.style.left=newLeft+"px";headDiv.style.top=newTop+"px";headDiv.style.height=parseInt(newHeight)+"px";headDiv.style.width=parseInt(newWidth)+"px";
this.updateControlsPosition();this.onResize();this.onDrag();}
CropController.prototype.getParameters=function(){
var parameters=new Array();var transformationsList=new Array();var metaData=new Array();
var zoneDiv=document.getElementById("Crop_ZoneDiv");
this.parameters["top"]=parseInt(zoneDiv.style.top);this.parameters["left"]=parseInt(zoneDiv.style.left);this.parameters["newWidth"]=parseInt(zoneDiv.style.width);this.parameters["newHeight"]=parseInt(zoneDiv.style.height);
this.parameters["X1"]=Math.round(this.parameters["left"] / this.ratio);this.parameters["X2"]=Math.round((this.parameters["left"]+this.parameters["newWidth"])/ this.ratio);this.parameters["Y1"]=Math.round(this.parameters["top"] / this.ratio);this.parameters["Y2"]=Math.round((this.parameters["top"]+this.parameters["newHeight"])/ this.ratio);
if(this.parameters["X1"]<0){this.parameters["X1"]=0;}
if(this.parameters["X2"]>=this.parameters["mediaWidth"]){this.parameters["X2"]=this.parameters["mediaWidth"]-1;}
if(this.parameters["Y1"]<0){this.parameters["Y1"]=0;}
if(this.parameters["Y2"]>=this.parameters["mediaHeight"]){this.parameters["Y2"]=this.parameters["mediaHeight"]-1;}
metaData["width"]=Math.round(this.parameters["X2"]-this.parameters["X1"]);metaData["height"]=Math.round(this.parameters["Y2"]-this.parameters["Y1"]);
transformationsList.push({"crop":{"x1":this.parameters["X1"],"x2":this.parameters["X2"],"y1":this.parameters["Y1"],"y2":this.parameters["Y2"]}});
parameters["metaData"]=metaData;parameters["transformationsList"]=transformationsList;
return parameters;}
CropController.prototype.setParameters=function(parameters,isForcedUpdate){
isForcedUpdate=isForcedUpdate==undefined?false : true;
this.parameters=MapUtils.putAll(this.parameters,parameters);
if(this.isGenerated&&!this.parameters["isBackAction"]){this.getWorkingImage();}
if(isForcedUpdate){this.updateUserInterface();}}
CropController.prototype.hide=function(){}
function FaceMappingController(id){jsClass.extend(this,[WizardController]);
this.id=id;return this;}
FaceMappingController.prototype.id="FaceMappingController";FaceMappingController.prototype.isUnique=true;FaceMappingController.prototype.isRunning=false;
FaceMappingController.prototype.init=function(){
this.super_WizardController_init();
Workspace.events.addListener(Workspace.events.EVENT_MODEL_ATTRIBUTES_CHANGED,this);Workspace.events.addListener(Workspace.events.EVENT_FACEMAPPING_START,this);Workspace.events.addListener(Workspace.events.EVENT_FACEMAPPING_END,this);}
FaceMappingController.prototype.stepStart=function(){
Workspace.events.throwEvent(Workspace.events.EVENT_FACEMAPPING_START,this);
if(document.getElementById("FaceMappingNextButton")!=undefined){document.getElementById("FaceMappingNextButton").innerHTML="Next Step";}
this.userObject=MyContent.userContent[MyContent.activeContentId];
ParserUtils.applyTemplate("FaceMappingPreviewTemplate","FaceMappingPreviewContainer",this);
if(typeof("Crop")!="undefined"&&Crop.isGenerated){document.getElementById("Crop_WholeImage").src="/images/spacer.gif";}
if(typeof("Tracer")!="undefined"&&Tracer.isGenerated){document.getElementById("TracerImage").src="/images/spacer.gif";}
if(typeof("MoveResize")!="undefined"&&MoveResize.isGenerated){document.getElementById("MoveResize_HeadImage").src="/images/spacer.gif";}
this.loadBackgroundModelImage();
this.nextStep();}
FaceMappingController.prototype.loadBackgroundModelImage=function(){
Model.requestModelInfo(undefined,{imageElementId:this.id+"_ModelImage",imageSize:Model.LARGE_IMAGE_SOURCE,imageWidth:Model.largeImageWidth,imageHeight:Model.largeImageHeight
,viewId:"1",isDefaultWear:"true",fileNamingMode:"BODY_WITHOUT_HEAD"});}
FaceMappingController.prototype.updateBackgroundModelImages=function(){
if(typeof(MoveResize)!="undefined"){MoveResize.updateBackgroundModelImage();}
if(typeof(ColorShift)!="undefined"){ColorShift.updateBackgroundModelImage();}
if(typeof(ColorAdjust)!="undefined"){ColorAdjust.updateBackgroundModelImage();}
if(document.getElementById("FaceMappingPreviewBody")!=undefined){document.getElementById("FaceMappingPreviewBody").src=document.getElementById("FaceMapping_ModelImage").src;}}
FaceMappingController.prototype.stepCrop=function(){
if(document.getElementById("FaceMappingNextButton")!=undefined){document.getElementById("FaceMappingNextButton").innerHTML="Next Step";}
Crop.setParameters({mediaId:this.userObject["OBJECT_ID"],mediaWidth:MapUtils.getMapValue("activeContextMap/ORIGINAL/width",this.userObject),mediaHeight:MapUtils.getMapValue("activeContextMap/ORIGINAL/height",this.userObject),transformationsList:[],isBackAction:this.isBackAction});
loopUntil("document.getElementById('CropPanel')!=undefined",escape("Anim.openSingle('CropPanel');"));
ParserUtils.setContainerHtml(this.id+"Instructions","Select the section of the picture you want to use as your face.<p/><li>Drag and resize the box and click next</li>");}
FaceMappingController.prototype.stepTracer=function(){
if(document.getElementById("FaceMappingNextButton")!=undefined){document.getElementById("FaceMappingNextButton").innerHTML="Next Step";
if(!this.isBackAction){document.getElementById("FaceMappingNextButton").disabled=false;}}
Tracer.setParameters({mediaId:this.userObject["OBJECT_ID"],mediaWidth:MapUtils.getMapValue("metaData/width",Crop.getParameters()),mediaHeight:MapUtils.getMapValue("metaData/height",Crop.getParameters()),transformationsList:Crop.getParameters()["transformationsList"],cacheId:this.id+"ResampledImage",isBackAction:this.isBackAction});
loopUntil("document.getElementById('TracerPanel')!=undefined",escape("Anim.openSingle('TracerPanel');"));
ParserUtils.setContainerHtml(this.id+"Instructions","Trace the contour of your face using the following instructions:<p/><li>Click on the center of your face(ie. your nose)</li><br/><li>Click on the hair contour,and move your mouse to start tracing the contour. Click again when done tracing.</li><br/><li>If the flashing contour is satisfactory,click on the Next Step button. Otherwise,click on the contour again and retouch the contour.</li>");}
FaceMappingController.prototype.stepMoveResize=function(){
if(document.getElementById("FaceMappingNextButton")!=undefined){document.getElementById("FaceMappingNextButton").innerHTML="Next Step";
if(!this.isBackAction){document.getElementById("FaceMappingNextButton").disabled=true;}}
var cropParams=Tracer.getParameters()["transformationsList"][3]["crop"];
MoveResize.setParameters({mediaId:this.id+"ResampledImage",mediaWidth:cropParams["x2"]-cropParams["x1"],mediaHeight:cropParams["y2"]-cropParams["y1"],transformationsList:Tracer.getParameters()["transformationsList"],metaData:Tracer.getParameters()["metaData"],cacheId:this.id+"ImageTraced",isBackAction:this.isBackAction});
Anim.openSingle("MoveResizePanel");
ParserUtils.setContainerHtml(this.id+"Instructions","Align your face over the model's neck and resize to adjust its proportion. Use Shift button on your keyboard while dragging the mouse to adjust the width and height.");}
FaceMappingController.prototype.stepColorShift=function(){
if(!this.isBackAction){Workspace.showWait();}
if(document.getElementById("FaceMappingNextButton")!=undefined){document.getElementById("FaceMappingNextButton").innerHTML="Next Step";}
ColorShift.setParameters({mediaId:this.id+"ImageTraced",transformationsList:MoveResize.getParameters()["transformationsList"],metaData:MapUtils.putAll(Tracer.getParameters()["metaData"],MoveResize.getParameters()["metaData"]),isBackAction:this.isBackAction});
Anim.openSingle("ColorShiftPanel");
ParserUtils.setContainerHtml(this.id+"Instructions","Use the sliders to match your face skin tone with the model's.");}
FaceMappingController.prototype.stepColorAdjust=function(){
Workspace.showWait();
if(document.getElementById("FaceMappingNextButton")!=undefined){document.getElementById("FaceMappingNextButton").innerHTML="Next Step";}
ColorAdjust.setParameters({mediaId:"FaceMappingImageTraced",transformationsList:MoveResize.getParameters()["transformationsList"],metaData:MapUtils.putAll(Tracer.getParameters()["metaData"],MoveResize.getParameters()["metaData"]),isBackAction:this.isBackAction});
Anim.openSingle("ColorAdjustPanel");
ParserUtils.setContainerHtml(this.id+"Instructions","Please select the image matching the body color the best.");}
FaceMappingController.prototype.stepPreview=function(){
Anim.openSingle('FaceMappingPreviewPanel');
Workspace.showWait();
if(document.getElementById("FaceMappingNextButton")!=undefined){document.getElementById("FaceMappingNextButton").innerHTML="Finish";}
var MoveResizeParameters=MoveResize.getParameters();var TracerParameters=Tracer.getParameters();
var transformationsList=new Array();transformationsList.push({"convert":{"fmt":"png"}});transformationsList=transformationsList.concat(MoveResizeParameters["transformationsList"]);
if(typeof(ColorShift)!="undefined"){transformationsList=transformationsList.concat(ColorShift.getParameters()["transformationsList"]);}else if(typeof(ColorAdjust)!="undefined"){transformationsList=transformationsList.concat(ColorAdjust.getParameters()["transformationsList"]);}
var previewUrl=Media.getImageUrl(
"FaceMappingImageTraced",Media.serializeTransformations(transformationsList),"FaceMappingFinalResult");
var faceImg=document.getElementById("FaceMappingPreviewImage");
faceImg.style.left=(parseInt(MoveResizeParameters["metaData"]["positionX"])+parseInt(document.getElementById("FaceMappingPreviewBody").style.left))+"px";faceImg.style.top=(parseInt(MoveResizeParameters["metaData"]["positionY"])+parseInt(document.getElementById("FaceMappingPreviewBody").style.top))+"px";faceImg.style.width=(parseInt(transformationsList[1]["resize"]["w"]))+"px";faceImg.style.height=(parseInt(transformationsList[1]["resize"]["h"]))+"px";
if(navigator.userAgent.indexOf("MSIE 6.0")>-1){faceImg.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+previewUrl+"',sizingMethod='image')";faceImg.src="/images/spacer.gif";}
else{faceImg.src=previewUrl;}
ParserUtils.setContainerHtml(this.id+"Instructions","Click Finish to publish the face mapping to your virtual model.");}
FaceMappingController.prototype.stepPublish=function(){
Workspace.events.throwEvent(Workspace.events.EVENT_FACEMAPPING_END,this);
var MoveResizeMetaData=MoveResize.getParameters()["metaData"];
MyContent.publishMedia("faceMapping",this.userObject["OBJECT_ID"],{"mediaId":"FaceMappingFinalResult","faceLeft":parseInt(parseInt(MoveResizeMetaData["positionX"])),"faceTop":parseInt(parseInt(MoveResizeMetaData["positionY"])),"canvasWidth":Model.largeImageWidth,"canvasHeight":Model.largeImageHeight,"isUserContextUnique":this.isUnique});
Anim.reset(this.id+"Panel");}
FaceMappingController.prototype.show=function(){
if(!this.isGenerated){
this.isGenerated=true;ParserUtils.applyTemplate(this.id+"Template",this.id+"Container");}
if(this.isInitialized){
this.currentStepIndex=0;this.showStep(0);}}
FaceMappingController.prototype.cancel=function(){
}
FaceMappingController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_MODEL_ATTRIBUTES_CHANGED&&this.isRunning){this.loadBackgroundModelImage();}
else if(eventKey==Workspace.events.EVENT_FACEMAPPING_START){this.isRunning=true;}
else if(eventKey==Workspace.events.EVENT_FACEMAPPING_END){this.isRunning=false;}}
function MediaController(id){
this.id=id;}
MediaController.prototype.id="MediaController";MediaController.prototype.cacheMap=undefined;
MediaController.prototype.init=function(){
this.cacheMap=new Array();}
MediaController.prototype.loadImage=function(sourceMediaId,transformations,cacheId,imageElementId){
var imgElement=document.getElementById(imageElementId);if(imgElement!=undefined){imgElement.src=this.getImageUrl(sourceMediaId,transformations,cacheId);}else{log.error("loadImage: Could not find image element ID: "+imageElementId,this);}}
MediaController.prototype.getImageUrl=function(sourceMediaId,transformations,cacheId,isUseCache){
isUseCache=(isUseCache!=undefined?isUseCache : false);
var imageUrl=Workspace.serverContext+"/action/getMedia?"+
"mId="+sourceMediaId+(cacheId!=undefined?"&cId="+cacheId : "")+(transformations!=undefined&&transformations!=""?"&tList="+transformations : "")+(!isUseCache?"&rnd="+Math.random(0): "");
log.debug("Getting media from server: "+imageUrl,this);
return imageUrl;}
MediaController.prototype.serializeTransformations=function(transformationsList){
var serializedTransformations="";
for(var index in transformationsList){
for(var transformationId in transformationsList[index]){
serializedTransformations+=(serializedTransformations!=""?"|" : "")+transformationId;
for(var tranformationParameterId in transformationsList[index][transformationId]){serializedTransformations+=";"+tranformationParameterId+":"+transformationsList[index][transformationId][tranformationParameterId];}}}
if(serializedTransformations==""){serializedTransformations=undefined;}
return serializedTransformations;}
function MoveResizeController(id){
this.id=id;return this;}
MoveResizeController.prototype.isGenerated=false;MoveResizeController.prototype.mediaId=2;MoveResizeController.prototype.arrayControls=undefined;MoveResizeController.prototype.faceImage=undefined;MoveResizeController.prototype.faceImageContainerId=undefined;MoveResizeController.prototype.originalImageRatio=undefined;MoveResizeController.prototype.originalImageX=0;MoveResizeController.prototype.originalImageY=0;MoveResizeController.prototype.parameters={"positionX":20,"positionY":120,"mediaWidth":0,"mediaHeight":0,"newWidth":0,"newHeight":0};MoveResizeController.prototype.id="MoveResizeController";MoveResizeController.prototype.widthControlId="MoveResize_Width_Control";MoveResizeController.prototype.heightControlId="MoveResize_Height_Control";MoveResizeController.prototype.scaleControlId="MoveResize_Scale_Control";MoveResizeController.prototype.controlCorrection=7;MoveResizeController.prototype.ratio=1.0;MoveResizeController.prototype.isImageLoaded=false;MoveResizeController.prototype.headMinOpacity=50;
MoveResizeController.prototype.init=function(){
resource.applyProperties(this.id+"Properties",this);}
MoveResizeController.prototype.show=function(){
if(!this.isGenerated){ParserUtils.applyTemplate(this.id+"Template",this.id+"Container",this,"MoveResize.generate();MoveResize.reset();MoveResize.isGenerated=true;");}else{if(!this.parameters["isBackAction"]){this.generate();this.reset();}}}
MoveResizeController.prototype.generate=function(){
this.isGenerated=true;
this.originalImageHeight=this.parameters["mediaHeight"];this.originalImageWidth=this.parameters["mediaWidth"];
this.updateBackgroundModelImage();this.getWorkingImage();this.setHeadSize(this.parameters["newWidth"],this.parameters["newHeight"]);MoveResize.setupDragAndDrop();
this.onResize();}
MoveResizeController.prototype.setInitialParameters=function(){
var bodyDiv=document.getElementById("MoveResize_Body");var modelImage=document.getElementById("MoveResize_ModelImage");var headImage=document.getElementById("MoveResize_HeadImage");var headDiv=document.getElementById("MoveResize_HeadDiv");
this.parameters["newWidth"]=100;this.parameters["newHeight"]=Math.round(100 *(this.originalImageHeight/this.originalImageWidth));
this.parameters["positionX"]=getWidth(modelImage)/2-(parseInt(this.parameters["newWidth"])/2);this.parameters["positionY"]=100-parseInt((this.parameters["newHeight"]/2));}
MoveResizeController.prototype.reset=function(){
this.setInitialParameters();this.updateUserInterface();}
MoveResizeController.prototype.updateBackgroundModelImage=function(){
if(document.getElementById(this.id+"_ModelImage")==undefined){loopUntil("document.getElementById("+this.id+"_ModelImage')!=undefined",this.id+".updateBackgroundModelImage()");}else{document.getElementById(this.id+"_ModelImage").src=document.getElementById("FaceMapping_ModelImage").src;}}
MoveResizeController.prototype.getWorkingImage=function(){
var headImage=document.getElementById("MoveResize_HeadImage");var moveResizeImageLoader=document.getElementById("MoveResize_imageLoader");var transformationsList=new Array();this.isImageLoaded=false;
var headImageUrl=Media.getImageUrl(
this.parameters["mediaId"],Media.serializeTransformations(this.parameters["transformationsList"].concat(transformationsList.concat())),this.parameters["cacheId"]);
if(!this.parameters["isBackAction"]){Workspace.showWait();}
moveResizeImageLoader.src=headImageUrl;
loopUntil(this.id+".isImageLoaded==true",escape(this.id+".showImage();"));}
MoveResizeController.prototype.showImage=function(){
var headImage=document.getElementById("MoveResize_HeadImage");var moveResizeImageLoader=document.getElementById("MoveResize_imageLoader");
if(navigator.userAgent.indexOf("MSIE 6")>-1){headImage.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+moveResizeImageLoader.src+"',sizingMethod='scale')"}else{headImage.src=moveResizeImageLoader.src;}
document.getElementById("FaceMappingNextButton").disabled=false;
Workspace.hideWait();}
MoveResizeController.prototype.setHeadSize=function(newWidth,newHeight,isPreservedRatio){
var headDiv=document.getElementById("MoveResize_HeadDiv");var ratio=1.0;
if(isPreservedRatio){
ratio=this.originalImageWidth / parseFloat(newWidth);
headDiv.style.height=Math.round(this.originalImageHeight * ratio)+"px";headDiv.style.width=Math.round(this.originalImageWidth * ratio)+"px";}else{
headDiv.style.height=parseInt(newHeight)+"px";headDiv.style.width=parseInt(newHeight)+"px";}
}
MoveResizeController.prototype.setupDragAndDrop=function(){
var bodyDiv=document.getElementById("MoveResize_Body");var headImage=document.getElementById("MoveResize_HeadImage");var headDiv=document.getElementById("MoveResize_HeadDiv");
var params=new Array();
params={isResetOnDrop:false,containerElementId:bodyDiv.id,onDrag:"MoveResize.onDrag()"
};
if(navigator.userAgent.indexOf("MSIE 6")==-1){params["onPick"]="MoveResize.setHeadOpacity("+this.headMinOpacity+")";params["onDrop"]="MoveResize.setHeadOpacity(100)";}
DragDrop.doDrag(headDiv.id,params);DragDrop.doDrag(this.scaleControlId,{isResetOnDrop:false,onDrag:"MoveResize.onDragScaleControl()",onDrop:"MoveResize.updateControlsPosition()"});
this.updateUserInterface();}
MoveResizeController.prototype.setHeadOpacity=function(opacity){
var headImage=document.getElementById("MoveResize_HeadImage");Anim.setOpacity(headImage,opacity);}
MoveResizeController.prototype.updateUserInterface=function(){
var headDiv=document.getElementById("MoveResize_HeadDiv");var bodyImage=document.getElementById("MoveResize_ModelImage");
headDiv.style.width=this.parameters["newWidth"]+"px";headDiv.style.height=this.parameters["newHeight"]+"px";
headDiv.style.left=(this.parameters["positionX"]+parseInt(bodyImage.style.left))+"px";headDiv.style.top=(this.parameters["positionY"]+parseInt(bodyImage.style.top))+"px";
if(headDiv.sizeMap==undefined){headDiv.sizeMap=new Array();}
headDiv.sizeMap["height"]=this.parameters["newHeight"];headDiv.sizeMap["width"]=this.parameters["newWidth"];
this.updateControlsPosition();}
MoveResizeController.prototype.updateControlsPosition=function(){
var headDiv=document.getElementById("MoveResize_HeadDiv");
document.getElementById(this.scaleControlId).style.top=(parseInt(headDiv.style.height)+parseInt(headDiv.style.top)-this.controlCorrection)+"px";document.getElementById(this.scaleControlId).style.left=(parseInt(headDiv.style.width)+parseInt(headDiv.style.left)-this.controlCorrection)+"px";
var newLeft=parseInt(headDiv.style.width)+parseInt(headDiv.style.left)-this.controlCorrection;
if(newLeft<headDiv.style.left){newLeft=headDiv.style.left;}
var newTop=(parseInt(headDiv.style.height)/ 2)+parseInt(headDiv.style.top)-this.controlCorrection;}
MoveResizeController.prototype.onResize=function(){
var headDiv=document.getElementById("MoveResize_HeadDiv");
MoveResize.parameters["newWidth"]=parseInt(headDiv.style.width);MoveResize.parameters["newHeight"]=parseInt(headDiv.style.height);}
MoveResizeController.prototype.onDrag=function(){
DragDrop.disable("MoveResize_HeadDiv");
var headDiv=document.getElementById("MoveResize_HeadDiv");
MoveResize.parameters["positionX"]=parseInt(headDiv.style.left);MoveResize.parameters["positionY"]=parseInt(headDiv.style.top);
this.updateControlsPosition();
DragDrop.enable("MoveResize_HeadDiv");}
MoveResizeController.prototype.onDragScaleControl=function(){
var headDiv=document.getElementById("MoveResize_HeadDiv");var bodyDiv=document.getElementById("MoveResize_Body");var scaleControl=document.getElementById(this.scaleControlId);
DragDrop.disable("MoveResize_HeadDiv");
if(headDiv.sizeMap==undefined){this.ratio=parseInt(headDiv.style.height)/ parseInt(headDiv.style.width);}else{this.ratio=headDiv.sizeMap["height"] / headDiv.sizeMap["width"];}
var controlLeft=parseInt(scaleControl.style.left);
if(controlLeft<(parseInt(headDiv.style.left))){controlLeft=(parseInt(headDiv.style.left));}
var newWidth=controlLeft-(parseInt(headDiv.style.left))+this.controlCorrection;
var widthDiff=newWidth-headDiv.sizeMap["width"];newWidth+=widthDiff;
if(newWidth<20){newWidth=20;widthDiff=0;}
if(newWidth>(parseInt(bodyDiv.style.width)-20)){widthDiff=0;newWidth=parseInt(bodyDiv.style.width)-20;}
var newHeight=parseFloat(this.ratio * newWidth);
if(headDiv.sizeMap==undefined){headDiv.sizeMap=new Array();}
headDiv.sizeMap["width"]=newWidth;headDiv.sizeMap["height"]=newHeight;
headDiv.style.height=parseInt(newHeight)+"px";headDiv.style.width=parseInt(newWidth)+"px";
var newTop=(parseInt(headDiv.style.top)-widthDiff);var newLeft=(parseInt(headDiv.style.left)-widthDiff);
if(newTop<0){newTop=0;}
if(newLeft<0){newLeft=0;}
if(newLeft>(parseInt(bodyDiv.style.width)+parseInt(bodyDiv.style.left))-newWidth-20){newLeft=(parseInt(bodyDiv.style.width)+parseInt(bodyDiv.style.left))-newWidth-20}
if(newTop>(parseInt(bodyDiv.style.height)+parseInt(bodyDiv.style.top))-newHeight-20){newTop=(parseInt(bodyDiv.style.height)+parseInt(bodyDiv.style.top))-newHeight-20}
headDiv.style.left=newLeft+"px";headDiv.style.top=newTop+"px";
this.updateControlsPosition();this.onResize();this.onDrag();
DragDrop.enable("MoveResize_HeadDiv");}
MoveResizeController.prototype.getParameters=function(){
var parameters=new Array();var transformationsList=new Array();
var headDiv=document.getElementById("MoveResize_HeadDiv");
this.parameters["positionX"]=parseInt(headDiv.style.left)-parseInt(document.getElementById(this.id+"_ModelImage").style.left);this.parameters["positionY"]=parseInt(headDiv.style.top)-parseInt(document.getElementById(this.id+"_ModelImage").style.top);this.parameters["newWidth"]=parseInt(headDiv.style.width);this.parameters["newHeight"]=parseInt(headDiv.style.height);
transformationsList.push({"resize":{"w":this.parameters["newWidth"],"h":this.parameters["newHeight"]}});transformationsList.push({"convert":{"fmt":"png"}});
parameters["metaData"]=new Array();
parameters["transformationsList"]=transformationsList;
parameters["metaData"]["positionX"]=this.parameters["positionX"];parameters["metaData"]["positionY"]=this.parameters["positionY"];
return parameters;}
MoveResizeController.prototype.setParameters=function(parameters,isForcedUpdate){
isForcedUpdate=isForcedUpdate==undefined?false : true;
this.parameters=MapUtils.putAll(this.parameters,parameters);
if(isForcedUpdate){this.updateUserInterface();}}
function MyContentController(id){
this.id=id;}
MyContentController.prototype.id="MyContentController";MyContentController.prototype.uploadState="";MyContentController.prototype.isGenerated=false;MyContentController.prototype.activeContentId=undefined;MyContentController.prototype.userContent=undefined;MyContentController.prototype.messageReferenceId=undefined;MyContentController.prototype.storageUsage=0;MyContentController.prototype.totalUserStorage=0;MyContentController.prototype.maxContextPerImage=5;MyContentController.prototype.lastUploadedContentId="";MyContentController.prototype.callout="MyContentCallout";
MyContentController.prototype.FEATURE_FACE_MAPPING="FEATURE_FACE_MAPPING";MyContentController.prototype.FEATURE_MODEL_OVERLAY="FEATURE_MODEL_OVERLAY";MyContentController.prototype.FEATURE_TRASH="FEATURE_TRASH";
MyContentController.prototype.init=function(){
Workspace.activateController("Media");
loopUntil(typeof(Media)!="undefined"&&typeof(DragDrop)!="undefined");
resource.applyProperties(this.id+"Properties",this);}
MyContentController.prototype.show=function(){
if(Workspace.user.isAuthenticated){
if(!this.isGenerated){this.isGenerated=true;
Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);Workspace.events.addListener(Workspace.events.EVENT_UPLOAD_STARTED,this);Workspace.events.addListener(Workspace.events.EVENT_UPLOAD_COMPLETED,this);Workspace.events.addListener(Workspace.events.EVENT_USER_SIGNIN,this);Workspace.events.addListener(Workspace.events.EVENT_USER_SIGNOUT,this);
ParserUtils.applyTemplate(this.id+"Template",this.id+"Container",undefined,this.id+".loadContent()");}else{this.loadContent();}
}else if(Workspace.user.isSignedIn){Workspace.events.addListener(Workspace.events.EVENT_USER_AUTHENTICATED,this);Workspace.user.displayAuthentication();
}else if(!this.isGenerated){Workspace.events.addListener(Workspace.events.EVENT_USER_SIGNIN,this);Workspace.message.displayMessage(resource.get("userNotSignedIn"));}}
MyContentController.prototype.loadContent=function(){
this.generate();this.sendRequest("getUserContent");}
MyContentController.prototype.generate=function(){
ParserUtils.applyTemplate(this.id+"ItemTemplate",this.id+"ItemContainer");
this.initUploadPanel();}
MyContentController.prototype.initUploadPanel=function(){
if(Workspace.user.isAuthenticated){document.getElementById(this.id+"Frame").src=Workspace.templatePath+"/UploadFormTemplate.html";}else{document.getElementById(this.id+"Frame").src="/images/spacer.gif";}}
MyContentController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_MEDIA_UPLOAD_STARTED){}}
MyContentController.prototype.applyContextToMedia=function(contextId,contentObjectId,attributes){
if(contentObjectId!=undefined){this.activeContentId=contentObjectId;
var totalContexts=0;
for(key in this.userContent[contentObjectId]['CONTEXT_PROPERTIES']){totalContexts++;}
if(attributes==undefined){if(totalContexts<this.maxContextPerImage){if(contextId==this.FEATURE_FACE_MAPPING){Anim.openSingle("FaceMappingPanel");}
else if(contextId==this.FEATURE_MODEL_OVERLAY){Anim.openSingle("OverlayPanel");}}
else{this.callout=Workspace.message.displayMessage({"message":ParserUtils.parseHtml(resource.get("MyContent.Context.LimitPerImageReached"),this),"duration":0,"isClosableOnClick":true});}
}else{
this.publishMedia(contextId,contentObjectId,attributes);}}
}
MyContentController.prototype.setContextAttribute=function(contentObjectId,contextId,attributeId,value){
var attributes=new Array();attributes["uoId"]=contentObjectId;attributes["contexts"]="ctxId:"+contextId+";"+attributeId+":"+value
this.sendRequest("updateUserContext",attributes);}
MyContentController.prototype.publishMedia=function(contextId,contentObjectId,attributes){
ModelQuestionnaire.save();
attributes["role"]=contextId;attributes["mId"]=attributes["mediaId"];attributes["uoId"]=contentObjectId;
this.sendRequest("addUserContext",attributes);}
MyContentController.prototype.deleteContent=function(contentObjectId,isForced){
if(contentObjectId!=undefined){isForced=(isForced==true?true : false);
if(isForced){
Anim.fadeOut(this.id+"Item_"+contentObjectId);this.sendRequest("deleteUserContent",{"uoId":contentObjectId});}else{this.callout=Workspace.message.displayMessage({"message":ParserUtils.parseHtml(resource.get("MyContent.Delete.Confirmation"),this),"templateId":"messageConfirmationTemplate","duration":0,"jsActionYes":this.id+".deleteContent('"+contentObjectId+"',true)","jsActionNo":"Workspace.message.hide('"+"messageObject"+Workspace.message.messageObjectCount+"')","isClosableOnClick":false});}}}
MyContentController.prototype.deleteContentContext=function(contentObjectId,contextId){
this.sendRequest("deleteUserContext",{"uoId":contentObjectId,"ctxId":contextId});}
MyContentController.prototype.setActiveContentId=function(contentId){
this.activeContentId=contentId;
ParserUtils.applyTemplate(this.id+"MediaInfoTemplate",this.id+"MediaInfoContainer");}
MyContentController.prototype.getContentIdFromElementId=function(elementId){
var element=document.getElementById(elementId);
if(element!=undefined&&element.getAttribute("objectId")!=undefined){return element.getAttribute("objectId");}else{return undefined;}}
MyContentController.prototype.addLastUploadedMediaToContent=function(){
if(Workspace.user.isAuthenticated){this.sendRequest("saveUserContent");}else{Workspace.message.displayMessage(resource.get("userNotSignedIn"));}}
MyContentController.prototype.setContent=function(userContent){
var role=undefined;var count=0;
this.userContent=userContent;this.storageUsage=0;
var context=undefined;
for(var contentId in this.userContent){
this.userContent[contentId]["activeContextMap"]=new Array();
for(var contextId in this.userContent[contentId]["CONTEXT_PROPERTIES"]){
context=this.userContent[contentId]["CONTEXT_PROPERTIES"][contextId];
if(context["POPULATION"]==undefined||(context["POPULATION"]==Workspace.population)){
if(context["IS_ENABLED"]==undefined||context["IS_ENABLED"]=="ON"){
this.userContent[contentId]["activeContextMap"][context["ROLE"]]=context;}
}else{delete this.userContent[contentId]["CONTEXT_PROPERTIES"][contextId];}
this.storageUsage+=context["size"]!=undefined?parseInt(context["size"]): 0;}
count++;}
var usagePercent=Math.floor(((this.storageUsage/1024)/this.totalUserStorage)*100);
document.getElementById(this.id+"StorageBar").style.width=(usagePercent/100)* parseInt(document.getElementById(this.id+"StoragePanel").style.width)+"px";document.getElementById(this.id+"StorageLabel").innerHTML=usagePercent+"%-"+Math.floor(this.storageUsage/1024)+" / "+this.totalUserStorage+" Kb";
if(document.all){document.getElementById(this.id+"CountLabel").innerText=count;}else{document.getElementById(this.id+"CountLabel").textContent=count;}
this.setActiveContentId((this.userContent[this.activeContentId]==undefined?contentId : this.activeContentId));
this.generate();
Model.requestModelInfo();}
MyContentController.prototype.sendRequest=function(actionType,parameters){
parameters=MapUtils.toArray(parameters);
det.sendRequest({serverUrl:Workspace.serverContext+"/action/"+actionType,action:actionType,parameters:parameters,callingController:this});}
MyContentController.prototype.catchEvent=function(eventKey,attributes){
if(attributes.callingController==this&&eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED&&attributes!=undefined&&attributes.response!=undefined&&attributes.response["userMyContent"]!=undefined){
if(attributes.action=="updateUserContext"||attributes.action=="addUserContext"){Model.setViewId(0,false);Model.requestModelInfo();}
if(attributes.response["userMyContentLimitSpace"]!=undefined){this.totalUserStorage=Math.round(parseInt(attributes.response["userMyContentLimitSpace"])/ 1024);}
if(attributes.response["addedContentId"]!=undefined){this.lastUploadedContentId=attributes.response["addedContentId"];}
if(attributes.action=="saveUserContent"){Workspace.events.throwEvent(Workspace.events.EVENT_CONTENT_CREATED,this);}
if(attributes.action=="deleteUserContent"){
Workspace.events.throwEvent(Workspace.events.EVENT_CONTENT_DELETED,attributes);}
this.setContent(attributes.response["userMyContent"]);
}else if(eventKey==Workspace.events.EVENT_UPLOAD_STARTED){
}else if(eventKey==Workspace.events.EVENT_UPLOAD_COMPLETED){
if(attributes["errorCode"]!=undefined){log.debug("Post Error: "+attributes["errorCode"],this);
if(attributes["errorCode"]=="UNEXPECTED"){this.callout=Workspace.message.displayMessage({message:resource.get(attributes["MyContent.Upload.Unsupported"]),messageObjectId:this.callout});}else{this.callout=Workspace.message.displayMessage({message:resource.get(attributes["errorCode"]),messageObjectId:this.callout});}}else{
setTimeout(this.id+".addLastUploadedMediaToContent()",500);}
this.initUploadPanel();
}else if(eventKey==Workspace.events.EVENT_USER_SIGNIN||eventKey==Workspace.events.EVENT_USER_AUTHENTICATED){this.show();
}else if(eventKey==Workspace.events.EVENT_USER_SIGNOUT){this.setContent(new Array());this.show();}
}
function OverlayController(id){jsClass.extend(this,[WizardController]);
this.id=id;return this;}
OverlayController.prototype.id="OverlayController";
OverlayController.prototype.stepStart=function(){
document.getElementById("OverlayNextButton").value="Finish";
this.userObject=MyContent.userContent[MyContent.activeContentId];
Model.requestModelInfo(undefined,{imageElementId:this.id+"_ModelImage",imageSize:Model.LARGE_IMAGE_SOURCE,imageWidth:Model.largeImageWidth,imageHeight:Model.largeImageHeight,CROPx1:0,CROPy1:0,CROPx2:1,CROPy2:1,viewId:"1",isDefaultWear:"true",fileNamingMode:"BODY_WITHOUT_HEAD"});
if(navigator.userAgent.indexOf("MSIE 6.0")>-1){
var previewUrl=Media.getImageUrl(
this.userObject["OBJECT_ID"],undefined,"OverlayFinalResult");
document.getElementById("Overlay_UserImage").style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+previewUrl+"',sizingMethod='image')";}else{
Media.loadImage(
this.userObject["OBJECT_ID"],undefined,"OverlayFinalResult","Overlay_UserImage");}
}
OverlayController.prototype.reset=function(){}
OverlayController.prototype.stepPublish=function(){
MyContent.publishMedia("faceMapping",this.userObject["OBJECT_ID"],{"mediaId":"OverlayFinalResult","faceLeft":0,"faceTop":0,"canvasWidth":Model.largeImageWidth,"canvasHeight":Model.largeImageHeight});
Anim.reset(this.id+"Panel");}
OverlayController.prototype.show=function(){
if(!this.isGenerated){
this.isGenerated=true;ParserUtils.applyTemplate(this.id+"Template",this.id+"Container",undefined,"Anim.open('"+this.id+"SubPanel');");}else{this.showStep(0)}
if(this.isInitialized){
this.currentStepIndex=0;this.showStep(0);}}
function TracerController(id){
this.id=id;}
TracerController.prototype.isGenerated=false;TracerController.prototype.jsGraphics=undefined;TracerController.prototype.defaultXCoordinates=undefined;TracerController.prototype.defaultYCoordinates=undefined;TracerController.prototype.xCoordinates=undefined;TracerController.prototype.yCoordinates=undefined;TracerController.prototype.isMouseDown=false;TracerController.prototype.isSelectingCenter=false;TracerController.prototype.imageWidth=400;TracerController.prototype.imageHeight=440;TracerController.prototype.displayedImageWidth=0;TracerController.prototype.displayedImageHeight=0;TracerController.prototype.polygonCenterX=undefined;TracerController.prototype.polygonCenterY=undefined;TracerController.prototype.messageId=undefined;TracerController.prototype.angleCount=90;TracerController.prototype.parameters=undefined;TracerController.prototype.leftMouseDisplacement=-5;TracerController.prototype.topMouseDisplacement=-8;TracerController.prototype.traceColor="green";
TracerController.prototype.init=function(){
this.defaultXCoordinates=[289,290,290,292,294,294,294,294,294,294,293,290,287,283,276,266,260,251,243,231,222,211,201,190,180,170,159,150,139,130,123,118,112,106,103,100,100,100,100,100,100,100,100,100,100,100,100,100,101,102,102,103,104,108,113,117,120,125,130,135,140,145,151,160,169,178,189,199,209,218,227,234,242,249,252,259,263,265,271,274,276,277,279,282,283,286,287,288,289,289,289];this.defaultYCoordinates=[197,190,184,177,169,162,156,145,137,127,116,107,97,88,82,75,69,61,56,55,55,55,55,55,55,55,55,58,60,63,75,84,92,100,111,120,131,141,150,158,165,173,180,188,195,202,209,216,221,230,238,246,252,259,266,273,279,288,293,300,311,321,330,338,341,343,344,344,342,336,330,324,318,310,301,294,287,283,274,266,260,252,247,240,233,227,221,215,209,203,200];
resource.applyProperties(this.id+"Properties",this);
this.xCoordinates=MapUtils.getClone(this.defaultXCoordinates);this.yCoordinates=MapUtils.getClone(this.defaultYCoordinates);}
TracerController.prototype.show=function(){
if(!this.isGenerated){ParserUtils.applyTemplate(this.id+"Template",this.id+"Container",undefined,this.id+".generate()");}else{this.generate();}}
TracerController.prototype.hide=function(){
}
TracerController.prototype.generate=function(){
if(this.jsGraphics==undefined){this.jsGraphics=new jsGraphics(this.id+"TraceOverlay");this.jsGraphics.setStroke(2);this.jsGraphics.setColor(this.traceColor);}
this.isSelectingCenter=true;
var newWidth=this.parameters["mediaWidth"];var newHeight=this.parameters["mediaHeight"];var tempRatio=1.0;var widthDiff=this.imageWidth-this.parameters["mediaWidth"];var heightDiff=this.imageHeight-this.parameters["mediaHeight"];
if(widthDiff<heightDiff){
tempRatio=this.imageWidth / newWidth;newWidth=this.imageWidth;newHeight=parseInt(newHeight * tempRatio);}else{
tempRatio=this.imageHeight / newHeight;newHeight=this.imageHeight;newWidth=parseInt(newWidth * tempRatio);}
newWidth=Math.round(newWidth);newHeight=Math.round(newHeight);
var transformationsList=this.parameters["transformationsList"];
transformationsList.push({"resize":{"w":newWidth,"h":newHeight}});transformationsList.push({"convert":{fmt:"jpg"}});
this.displayedImageWidth=newWidth;this.displayedImageHeight=newHeight;
if(!this.parameters["isBackAction"]){
Workspace.showWait();
Media.loadImage(
this.parameters["mediaId"],Media.serializeTransformations(transformationsList),this.parameters["cacheId"],"TracerImage");}
this.isSelectingCenter=false;
this.setOriginalCenterPoint();
if(!this.isGenerated){
/*
var centerElement=document.getElementById(this.id+"Center");if(centerElement!=undefined){centerElement.style.left=(centerLeft-parseInt(centerElement.style.width)/2)+"px";centerElement.style.top=(centerTop-parseInt(centerElement.style.height)/2)+"px";}
DragDrop.doDrag(this.id+"Center",{onPick:this.id+".isSelectingCenter=true;",onDrop:this.id+".isSelectingCenter=false;"+this.id+".setCenterPoint(parseInt(document.getElementById('"+this.id+"Center').style.left),parseInt(document.getElementById('"+this.id+"Center').style.top));"});*/
this.isGenerated=true;}
}
TracerController.prototype.setOriginalCenterPoint=function(){
var origImage=document.getElementById("TracerImage");
var imageTop=parseInt(origImage.style.top);var imageLeft=parseInt(origImage.style.left);
var centerLeft=Math.floor((this.displayedImageWidth/2)+imageLeft);var centerTop=Math.floor((this.displayedImageHeight/2)+imageTop);
this.setCenterPoint(centerLeft,centerTop);}
TracerController.prototype.reset=function(){
this.xCoordinates=MapUtils.getClone(this.defaultXCoordinates);this.yCoordinates=MapUtils.getClone(this.defaultYCoordinates);this.drawAllPoints();}
TracerController.prototype.drawAllPoints=function(){
this.jsGraphics.clear();document.getElementById(this.id+"PlotterOverlay").style.display="block";
for(var angle=0;angle<=this.angleCount;angle++){this.drawPoints(this.xCoordinates[angle],this.yCoordinates[angle],angle);}}
TracerController.prototype.setCenterPoint=function(left,top){
var deltaLeft=(this.polygonCenterX!=undefined?left-this.polygonCenterX : 0);var deltaTop=(this.polygonCenterY!=undefined?top-this.polygonCenterY : 0);
this.polygonCenterX=left;this.polygonCenterY=top;
this.jsGraphics.clear();
for(var angle=0;angle<=this.angleCount;angle++){
this.xCoordinates[angle]+=deltaLeft;this.yCoordinates[angle]+=deltaTop;
}}
TracerController.prototype.setParameters=function(map){
this.parameters=MapUtils.putAll(this.parameters,map);}
TracerController.prototype.getParameters=function(){
var parameters=new Array();var transformationsList=new Array();
var polygonInfo=new Array();polygonInfo["type"]="1";
transformationsList.push({"resize":{"w":this.displayedImageWidth,"h":this.displayedImageHeight}});
var xCoordinatesArray=new Array();var yCoordinatesArray=new Array();
for(var angle=0;angle<=this.angleCount;angle++){
if(this.xCoordinates[angle]<1){this.xCoordinates[angle]=1;}
if(this.xCoordinates[angle]>=this.displayedImageWidth){this.xCoordinates[angle]=this.displayedImageWidth-1;}
if(this.yCoordinates[angle]<1){this.yCoordinates[angle]=1;}
if(this.yCoordinates[angle]>=this.displayedImageHeight){this.yCoordinates[angle]=this.displayedImageHeight-1;}
xCoordinatesArray.push(parseInt(this.xCoordinates[angle]));yCoordinatesArray.push(parseInt(this.yCoordinates[angle]));}
polygonInfo["x"]=xCoordinatesArray;polygonInfo["y"]=yCoordinatesArray;polygonInfo["sy"]="2";polygonInfo["sx"]="2";
transformationsList.push({"convert":{"fmt":"png"}});transformationsList.push({"trace":polygonInfo});
parameters["metaData"]={imageWidth:this.imageWidth,imageHeight:this.imageHeight};
var minX=65000;var maxX=0;var minY=65000;var maxY=0;
for(x in transformationsList[2]["trace"]["x"]){if(transformationsList[2]["trace"]["x"][x]>maxX){maxX=transformationsList[2]["trace"]["x"][x];}
if(transformationsList[2]["trace"]["x"][x]<minX){minX=transformationsList[2]["trace"]["x"][x];}}
for(y in transformationsList[2]["trace"]["y"]){if(transformationsList[2]["trace"]["y"][y]>maxY){maxY=transformationsList[2]["trace"]["y"][y];}
if(transformationsList[2]["trace"]["y"][y]<minY){minY=transformationsList[2]["trace"]["y"][y];}}
transformationsList.push({"crop":{x1:minX,x2:maxX,y1:minY,y2:maxY}});
parameters["transformationsList"]=transformationsList;
return parameters;}
TracerController.prototype.onMouseDown=function(e){
if(!this.isSelectingCenter){
if(!this.isMouseDown){
document.getElementById(this.id+"PlotterOverlay").style.display="block";this.jsGraphics.clear();}
this.isMouseDown=true;
document.ondragstart=function(){return false;};document.onselectstart=function(){return false;};}}
TracerController.prototype.onMouseUp=function(e){
this.isMouseDown=false;
this.drawPolygon();
document.ondragstart=function(){return true;};document.onselectstart=function(){return true;};}
TracerController.prototype.onMouseOver=function(e){
if(this.isMouseDown){
var mouse=getMouseState(e);
var mouseX=parseInt(mouse.left+this.leftMouseDisplacement-getAbsLeft(document.getElementById(this.id+"PlotterOverlay")));var mouseY=parseInt(mouse.top+this.topMouseDisplacement-getAbsTop(document.getElementById(this.id+"PlotterOverlay")));
if(mouseX<0){mouseX=0;}else if(mouseX>this.displayedImageWidth){mouseX=this.displayedImageWidth;}
if(mouseY<0){mouseY=0;}else if(mouseY>this.displayedImageHeight){mouseY=this.displayedImageHeight;}
anglex=Math.round(((Math.atan((this.polygonCenterX-mouseX)/(this.polygonCenterY-mouseY))* 180 / Math.PI)+this.angleCount+(mouseY>this.polygonCenterY?180 : 0))/(360/this.angleCount));
this.xCoordinates[anglex]=mouseX;this.yCoordinates[anglex]=mouseY;
this.drawPoints(mouseX,mouseY,anglex);}}
TracerController.prototype.drawPolygon=function(){
document.getElementById(this.id+"PlotterOverlay").style.display="none";
this.jsGraphics.clear();this.jsGraphics.drawPolygon(this.xCoordinates,this.yCoordinates);this.jsGraphics.paint();}
TracerController.prototype.drawPoints=function(currentX,currentY,angle){
var pointElement=document.getElementById(this.id+"Point"+angle);if(pointElement==undefined){
pointElement=document.createElement("img");pointElement.id=this.id+"Point"+angle;pointElement.className="plotterPoint";pointElement.style.left=currentX+"px";pointElement.style.top=currentY+"px";document.getElementById(this.id+"PlotterOverlay").appendChild(pointElement);}else{pointElement.style.left=currentX+"px";pointElement.style.top=currentY+"px";}}
TracerController.prototype.onMouseOut=function(e){}
function WizardController(id){
this.id=id;return this;}
WizardController.prototype.isGenerated=false;WizardController.prototype.isInitialized=false;WizardController.prototype.stepControllers=undefined;WizardController.prototype.stepCalls=undefined;WizardController.prototype.currentStepIndex=0;WizardController.prototype.userObject=undefined;WizardController.prototype.isBackAction=false;WizardController.prototype.id="WizardController";
WizardController.prototype.init=function(){
resource.applyProperties(this.id+"Properties",this);
this.initStepControllers(0);}
WizardController.prototype.initStepControllers=function(index){
var onComplete="";
if(index+1==this.stepControllers.length){onComplete=this.id+".isInitialized=true;"+this.id+".show()";}else{onComplete=this.id+".initStepControllers("+(index+1)+")";}
if(this.stepControllers[index]!=undefined){Workspace.activateController(this.stepControllers[index],undefined,onComplete);}}
WizardController.prototype.showStep=function(stepIndex){
eval(this.stepCalls[stepIndex]);}
WizardController.prototype.nextStep=function(){
this.currentStepIndex=(this.currentStepIndex+1<this.stepCalls.length?this.currentStepIndex+1 : this.currentStepIndex);this.isBackAction=false;
this.showStep(this.currentStepIndex);}
WizardController.prototype.previousStep=function(){
if(this.currentStepIndex>0){this.currentStepIndex=this.currentStepIndex-1;}
this.isBackAction=true;
this.showStep(this.currentStepIndex);}
WizardController.prototype.hide=function(){}
function ModelAppearanceController(id){
this.id=id;return this;}
ModelAppearanceController.prototype.id="ModelAppearanceController";ModelAppearanceController.prototype.categoryID=undefined;ModelAppearanceController.prototype.isEnabled=true;ModelAppearanceController.prototype.specialCategoryIDArray=undefined;ModelAppearanceController.prototype.validationKeyArray=undefined;ModelAppearanceController.prototype.defaultAppearanceMap=undefined;
ModelAppearanceController.prototype.init=function(){
Workspace.events.addListener(Workspace.events.EVENT_CATALOG_CATEGORY_CHANGED,this);
this.specialCategoryIDArray=new Array();this.validationKeyArray=["Ethnic","FudgeFactor","BodyShape","NoseShape","BustCup","LipShape","HairStyle_F_40","WaistShape","VMName","HairColor","AgeGroup","EyeShape"];
resource.applyProperties(this.id+"Properties",this);
var defaultModelAppearance=resource.get("ModelQuestionnaireProperties/defaultAnswersMap/"+Workspace.population);this.defaultAppearanceMap=new Array();
for(var index in this.validationKeyArray){this.defaultAppearanceMap[this.validationKeyArray[index]]=defaultModelAppearance[this.validationKeyArray[index]];}
if(this.isEnabled&&Workspace.viewData["externalTryonInfo"]!=undefined&&Workspace.viewData["externalTryonInfo"]["errorCode"]==undefined){
var categoryId=Workspace.viewData["externalTryonInfo"]["categoryInfo"]["CATEGORIES"][0]["CATEGORY_ID"];var stateAppearance=(State.get("appearance")!=undefined?MapUtils.getMapFromString(decodeURIComponent(State.get("appearance"))): undefined);
if(!Workspace.user.isSignedIn&&this.isSpecialCategory(categoryId)&&(stateAppearance==undefined||this.isSpecialAppearance(stateAppearance)||this.isDefaultAppearance(stateAppearance))){
ModelQuestionnaire.forcedAppearance=resource.get("ModelQuestionnaireProperties/specialAppearance/"+this.specialCategoryIDArray[categoryId]+"/"+Workspace.population);}}
Workspace.events.throwEvent(Workspace.events.EVENT_CONTROLLER_INITIALIZED,this);}
ModelAppearanceController.prototype.catchEvent=function(eventKey,attributes){
if(this.isEnabled){
if(eventKey==Workspace.events.EVENT_CATALOG_CATEGORY_CHANGED&&attributes!=undefined&&(this.isSpecialAppearance(ModelQuestionnaire.getAnswersMap())||this.isDefaultAppearance())){
var categoryId=attributes.displayedCategoryId;
if(this.isSpecialCategory(categoryId)){this.setSpecialAppearance(this.specialCategoryIDArray[categoryId]);
}else if(!ModelQuestionnaire.isDefaultAppearance()){}}}}
ModelAppearanceController.prototype.isSpecialAppearance=function(modelAppearance){
var isFound=false
for(var specialAppearanceId in ModelQuestionnaire.specialAppearance){
if(MapUtils.isMapEquals(modelAppearance,ModelQuestionnaire.specialAppearance[specialAppearanceId][Workspace.population],this.validationKeyArray),true){isFound=true;break;}}
return isFound;}
ModelAppearanceController.prototype.isDefaultAppearance=function(modelAppearance){
modelAppearance=(modelAppearance!=undefined?modelAppearance : ModelQuestionnaire.getAnswersMap());
return MapUtils.isMapEquals(modelAppearance,ModelQuestionnaire.defaultAnswersMap,this.validationKeyArray);}
ModelAppearanceController.prototype.setSpecialAppearance=function(key){
if(!MapUtils.isMapEquals(ModelQuestionnaire.getAnswersMap(),ModelQuestionnaire.specialAppearance[key][Workspace.population],this.validationKeyArray)){ModelQuestionnaire.setAnswersMap(ModelQuestionnaire.specialAppearance[key][Workspace.population],true);}}
ModelAppearanceController.prototype.setDefaultAppearance=function(){
if(!MapUtils.isMapEquals(ModelQuestionnaire.getAnswersMap(),this.defaultAppearanceMap,this.validationKeyArray)){ModelQuestionnaire.setAnswersMap(this.defaultAppearanceMap,true);}}
ModelAppearanceController.prototype.isSpecialCategory=function(serverCatID){
return(this.specialCategoryIDArray[serverCatID]!=undefined?true : false);}
function ModelController(id){
this.id=id;
return this;}
ModelController.prototype.SMALL_IMAGE_SOURCE="SMALL_IMAGE";ModelController.prototype.LARGE_IMAGE_SOURCE="LARGE_IMAGE";
ModelController.prototype.id="ModelController";ModelController.prototype.handlerUrl="";ModelController.prototype.modelImageUrl="/images/spacer.gif";ModelController.prototype.lastModelImageUrl="";ModelController.prototype.swatchURL="";ModelController.prototype.isInitialized=false;ModelController.prototype.isZoomedIn=false;ModelController.prototype.isEnlarged=false;ModelController.prototype.isZoomFeatureEnabled=false;ModelController.prototype.isInstanceSelectionMode=false;ModelController.prototype.isDefaultWear=false;ModelController.prototype.isAutomaticBestView=true;ModelController.prototype.isRestoreWornGarmentsFromCookie=true;ModelController.prototype.isOverPolygon=false;ModelController.prototype.isFirstModelDisplay=false;
ModelController.prototype.instancesInfo=undefined;ModelController.prototype.defaultBackgroundImageArray=new Array();ModelController.prototype._backgroundImageIndex=0;ModelController.prototype.backgroundImageUrl="";ModelController.prototype.viewId=1;ModelController.prototype.layoutId=0;ModelController.prototype.layoutIdArray=undefined;ModelController.prototype.viewCount=undefined;ModelController.prototype.defaultType="";ModelController.prototype.compositorAlgorithm="";ModelController.prototype.compositorQuality="";ModelController.prototype.compositorMapVersion="";ModelController.prototype.compositorBrightness="";ModelController.prototype.compositorContrast="";ModelController.prototype.compositorGamma="";ModelController.prototype.mouseOverActionThread=undefined;ModelController.prototype.garmentIdToMove=undefined;ModelController.prototype.defaultImageSource="SMALL_IMAGE";ModelController.prototype.lastActionParameters=undefined;ModelController.prototype.lastExternalTryOnGarmentId=undefined;ModelController.prototype.imageWidth="";ModelController.prototype.imageHeight="";ModelController.prototype.largeImageWidth="";ModelController.prototype.largeImageHeight="";ModelController.prototype.bodySet=undefined;ModelController.prototype.zoomFactor=2;ModelController.prototype.alternateItemAutoTryon=true;ModelController.prototype.defaultOutfit=undefined;ModelController.prototype.fileNamingMode=undefined;ModelController.prototype.appearanceOverride=undefined;ModelController.prototype.wornGarmentOverride=undefined;ModelController.prototype.modelImageTimeout=10000;ModelController.prototype.modelImageTimeoutUrl="/images/model_errors/error_modelcomplete.gif";ModelController.prototype.isGetCommonColors=false;ModelController.prototype.imageElementId="";
ModelController.prototype.content=undefined;
ModelController.prototype.rendererType=undefined;ModelController.prototype.focusGeometry=undefined;ModelController.prototype.camera=undefined;ModelController.prototype.lastCamera=undefined;ModelController.prototype.VMContext="";ModelController.prototype.layoutCameraPresets=undefined;ModelController.prototype.layoutSettings=undefined;ModelController.prototype.cameraPresetId=0;ModelController.prototype.afterBestViewAction=undefined;
ModelController.prototype.world="";
ModelController.prototype.init=function(){
if(typeof(ModelContentController)!="undefined"){this.content=new ModelContentController(this.id+".content",this);}
if(this.content.isInitialized==false){this.content.init();}
Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);Workspace.events.addListener(Workspace.events.EVENT_MODEL_ATTRIBUTES_CHANGED,this);Workspace.events.addListener(Workspace.events.EVENT_MODEL_MAP_LOADED,this);Workspace.events.addListener(Workspace.events.EVENT_CONTROLLER_INITIALIZED,this);Workspace.events.addListener(Workspace.events.EVENT_MODEL_IMAGE_CHANGED,this);
this.handlerUrl=Workspace.serverContext+"/action/";this.imageElementId=this.id+"Image";
resource.applyProperties(this.id+"Properties",this);
if(isNaN(parseInt(document.getElementById(this.imageElementId).style.width))){document.getElementById(this.imageElementId).style.width=this.imageWidth+"px";document.getElementById(this.imageElementId).style.height=this.imageHeight+"px";}
this.initModelState();}
ModelController.prototype.initModelState=function(){
var requestGroup=new Array();var garmentsIdToWear="";var isModelRequested=false;
this.isFirstModelDisplay=true;this.isZoomedIn=false;this.isEnlarged=false;this.isInstanceSelectionMode=false;this.rendererType=Workspace.viewData["rendererType"];
this.bodySet=(Workspace.viewData["bodysets"]!=undefined?Workspace.viewData["bodysets"] : new Array());
var layoutIndexCookie=State.get("layoutIndex");
if(Workspace.query.layoutId!=undefined){this.setLayoutId(Workspace.query.layoutId,false);}else if(layoutIndexCookie!=undefined){this.setLayout(layoutIndexCookie,false);}
if(this.rendererType=="RT3D"){Workspace.activateController("CameraControl","CameraController");this.camera=new Camera(this.id+".camera");}
this.setViewId(State.get("viewId"),false);this.setCameraPresetId(State.get("cameraPresetId"),false);
if(this.rendererType=="RT3D"){
if(this.layoutSettings[this.layoutId]!=undefined){this.camera.setBoundingBox(this.layoutSettings[this.layoutId]["boundingBox"]);this.camera.setTransitionPoint(this.layoutSettings[this.layoutId]["transitionPoint"]);this.camera.setLighting(this.layoutSettings[this.layoutId]["lighting"]);}else{log.error("no setting found for layout id : "+this.layoutId,this);}
if(this.layoutCameraPresets[this.layoutId]!=undefined){if(this.layoutCameraPresets[this.layoutId][0]!=undefined){this.camera.state=MapUtils.getClone(this.layoutCameraPresets[this.layoutId][0]["state"]);this.camera.focusGeometry=MapUtils.getClone(this.layoutCameraPresets[this.layoutId][0]["target"]);this.camera.setFocusAction(0);}else{log.error("no default preset found for layout id :"+this.layoutId,this);}}}
if(this.defaultBackgroundImageArray.length>0){this.setBackground(this.defaultBackgroundImageArray[0],false);}
if(!Workspace.user.isSignedIn&&Workspace.viewData["isAlreadyInitialized"]=="false"&&!Workspace.user.isAuthenticated&&typeof(ModelQuestionnaire)!="undefined"){
ModelQuestionnaire.update();}
var garmentsOnModelState=State.get("wornGarments");
this.initializeDefaultType();
if(!this.isInitialized&&this.isRestoreWornGarmentsFromCookie&&garmentsOnModelState!=undefined){
if(Workspace.viewData["isAlreadyInitialized"]=="false"||(Workspace.viewData["isAlreadyInitialized"]=="true"&&Workspace.lastVisitedSiteInfo!=location.href.toString())){
garmentsOnModelState=(garmentsOnModelState!=undefined?decodeURIComponent(garmentsOnModelState): "");
log.debug("setting model content with: "+garmentsOnModelState+" for restoring state",this);this.requestModelInfo("setContent",{garmentsID:garmentsOnModelState},false);}
}else if(!this.isInitialized&&(Workspace.viewData["isAlreadyInitialized"]=="false"||Workspace.isPopulationChange==true)&&garmentsOnModelState==undefined){
if(Workspace.viewData["itemsInfo"]!=undefined&&resource.get("StorageSolutionsProperties")!=""){passedCategory=Workspace.viewData["itemsInfo"]["CATEGORIES"][0]["CATEGORY_ID"];
if(resource.get("StorageSolutionsProperties")["catalogStorageCatArray"][passedCategory]!=undefined){passedDefaultType=resource.get("StorageSolutionsProperties")["catalogStorageCatArray"][passedCategory];Model.defaultType=passedDefaultType;}else{Model.defaultType="initial";}
State.set("storageCategory",Model.defaultType);}
this.putOnDefaultOutfit(false);}
var remoteAction=undefined;
if(!this.isInitialized&&Workspace.query.param1!=undefined&&Workspace.query.param1!=""){
storageCat=State.get("storageCategory");var passedDefaultType=undefined;
if(Workspace.viewData["isAlreadyInitialized"]=="true"&&Workspace.viewData["itemsInfo"]!=undefined&&resource.get("StorageSolutionsProperties")!=""){
passedCategory=Workspace.viewData["itemsInfo"]["CATEGORIES"][0]["CATEGORY_ID"];passedDefaultType=resource.get("StorageSolutionsProperties")["catalogStorageCatArray"][passedCategory];
if(passedDefaultType==storageCat||passedDefaultType==undefined){
if(passedDefaultType==undefined){Model.defaultType="initial";}
passedDefaultType=undefined;}
else{if(passedDefaultType!=undefined){Model.defaultType=passedDefaultType;}else{Model.defaultType="initial";}
this.putOnDefaultOutfit(false);}}
this.tryOnExternalItems(Workspace.query.param1,Workspace.query.param2,Workspace.query.param3,undefined,true);}else if(!this.isInitialized&&remoteAction!=undefined){
var remoteTryOnInfo=decodeURIComponent(remoteAction).match(/Model.tryOnExternalItems\((.*),(.*),(.*)\)/);
if(remoteTryOnInfo!=undefined){
remoteTryOnInfo[1]=(remoteTryOnInfo[1]=="undefined"?undefined : remoteTryOnInfo[1].match(/'?([^']*)/)[1]);remoteTryOnInfo[2]=(remoteTryOnInfo[2]=="undefined"?undefined : remoteTryOnInfo[2].match(/'?([^']*)/)[1]);remoteTryOnInfo[3]=(remoteTryOnInfo[3]=="undefined"?undefined : remoteTryOnInfo[3].match(/'?([^']*)/)[1]);
this.tryOnExternalItems(remoteTryOnInfo[1],remoteTryOnInfo[2],remoteTryOnInfo[3],undefined,true);}else{
this.requestModelInfo();}
}else{
this.requestModelInfo();}}
ModelController.prototype.initializeDefaultType=function(){
if(Workspace.query.DEFAULT_TYPE!=undefined){
this.setDefaultType(Workspace.query.DEFAULT_TYPE);}else if(State.get("startupDefaultType")!=undefined){this.setDefaultType(State.get("startupDefaultType"));}else{this.setDefaultType("initial");}}
ModelController.prototype.setDefaultType=function(defaultType){
this.defaultType=defaultType;State.set("startupDefaultType",defaultType);}
ModelController.prototype.setStyle=function(styleName,layoutId,param1,param2,param3){
if(layoutId!=undefined&&layoutId!=this.layoutId){this.setLayoutId(layoutId,false);}
this.setDefaultType(styleName);
if(param1!=undefined){this.putOnDefaultOutfit(false);this.isFirstModelDisplay=true;this.tryOnExternalItems(param1,param2,param3,undefined,true);}else{this.putOnDefaultOutfit(true);}}
ModelController.prototype.updateImage=function(imageUrl,imageElementId,isModelImageEventThrown){
isModelImageEventThrown=isModelImageEventThrown==undefined?true : isModelImageEventThrown;
this.isModelImageEventThrown=isModelImageEventThrown;
if(imageUrl!=""&&imageUrl!=undefined){
if(imageElementId==undefined){
if(this.modelImageUrl!=imageUrl){clearTimeout(this.timeoutThread);this.timeoutThread=setTimeout(this.id+".handleModelImageTimeout()",this.modelImageTimeout);}
this.modelImageUrl=imageUrl;imageElementId=this.imageElementId;
Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_IMAGE_LOADING,this);}
log.info("Loading model image into "+imageElementId+" : "+imageUrl,this);document.getElementById(imageElementId).src=imageUrl;}}
ModelController.prototype.updateLastCamera=function(){
if(this.camera!=undefined){this.lastCamera=new Camera();this.lastCamera.setCameraFrom(this.camera,true);}
}
ModelController.prototype.getUpdatedCompositorImageUrl=function(imageUrl){
if(imageUrl.indexOf("&")>-1){
imageUrl_1="&"+imageUrl.split("&")[1];
imageUrl=imageUrl.split("&")[0]+
"&im=y"+(this.compositorAlgorithm!=""?"&a="+this.compositorAlgorithm : "")+(this.compositorQuality!=""?"&q="+this.compositorQuality : "")+(this.compositorMapVersion!=""?"&mv="+this.compositorMapVersion : "");
if(this.compositorBrightness!=""||this.compositorContrast!=""||this.compositorGamma!=""){imageUrl+="&ic="+(this.compositorBrightness!=""?"b"+this.compositorBrightness : "")+(this.compositorContrast!=""?"c"+this.compositorContrast : "")+(this.compositorGamma!=""?"g"+this.compositorGamma : "");}
imageUrl+=imageUrl_1;}
return imageUrl;}
ModelController.prototype.getUpdatedMPSImageUrl=function(imageUrl){
if(imageUrl.indexOf("?")>-1){
imageUrl=imageUrl.split("?")[0]+"?m=r&"+imageUrl.split("?")[1]+"&"+this.camera.getMPSString();}
return imageUrl;}
ModelController.prototype.onImageLoad=function(imageElement){
clearTimeout(this.timeoutThread);
log.info(imageElement.id+" image loaded event",this);
if(this.isFirstModelDisplay){this.isFirstModelDisplay=false;this.isInitialized=true;Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_INITIALIZED,this);Workspace.events.throwEvent(Workspace.events.EVENT_CONTROLLER_INITIALIZED,this);}
if(this.afterBestViewAction!=undefined){
var tempAfterAction=this.afterBestViewAction;this.afterBestViewAction=undefined;eval(tempAfterAction);}
if(this.isModelImageEventThrown){Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_IMAGE_CHANGED,this);}else{this.isModelImageEventThrown=true;}}
ModelController.prototype.handleModelImageTimeout=function(){
log.error("Timeout when retreiving model image:"+this.modelImageUrl,this);
var activeImageElement=document.getElementById(this.imageElementId);activeImageElement.src=this.timeoutModelImageUrl}
ModelController.prototype.setBackground=function(backgroundImageUrl,isReloadModel){
this.backgroundImageUrl=backgroundImageUrl;
if(isReloadModel){this.requestModelInfo();}}
ModelController.prototype.cycleBackground=function(){
this._backgroundImageIndex++;
if(this._backgroundImageIndex>this.defaultBackgroundImageArray.length-1){this._backgroundImageIndex=0;}
this.setBackground(this.defaultBackgroundImageArray[this._backgroundImageIndex],true);}
ModelController.prototype.requestModelInfo=function(action,attributes,isGetModelImage){
this.disableInstanceSelectionMode();
attributes=attributes==undefined?new Array(): attributes;
if(typeof(ModelMap)!="undefined"&&ModelMap.isInstance){ModelMap.disable();}
action=(action!=undefined?action : "modelDisplay");isGetModelImage=(isGetModelImage!=undefined?isGetModelImage : true);
var params=new Array();
params["onMyModelFlag"]=(isGetModelImage?"TRUE" : "FALSE");params["viewId"]=this.viewId;params["layoutId"]=this.layoutId;params["isDefaultWear"]=this.isDefaultWear?"true" : "false";
if(this.fileNamingMode!=undefined){param["fileNamingMode"]=this.fileNamingMode;}
if(this.drMode!=undefined){params["drMode"]=this.drMode;}
if(this.backgroundImageUrl!=""){params["backgroundImageUrl"]=this.backgroundImageUrl;}
params["isGetCommonColors"]=this.isGetCommonColors;
if(this.appearanceOverride!=undefined){param["appearanceOverride"]=MapUtils.toJSON(this.appearanceOverride);}
if(this.wornGarmentOverride!=undefined){param["wornGarments"]=MapUtils.toJSON(this.wornGarmentOverride);}
if(this.isEnlarged||this.isZoomedIn){params["imageSize"]=this.LARGE_IMAGE_SOURCE;params["imageWidth"]=this.largeImageWidth;params["imageHeight"]=this.largeImageHeight;}else{params["imageSize"]=this.defaultImageSource;params["imageWidth"]=this.imageWidth;params["imageHeight"]=this.imageHeight;}
params=MapUtils.putAll(params,attributes);
this.lastActionParameters=params;this.sendRequest(action,params);}
/**
* Previews the user model with overrides of model attributes and/or worn garments
* @param{Map}modelAttributesmap of model appearance attributes ex: weight:330,hairstyle:2333
* @param{String}wornGarmentscomma-separated list of garment Ids
* @param{Boolean}isOneTimeOnlywhen true,the model changes will be lost next time the model is loaded. Otherwise,* the override will remain until resetOverride()is called.
*/
ModelController.prototype.preview=function(modelAttributes,wornGarments,isOneTimeOnly){
isOneTimeOnly=(isOneTimeOnly!=undefined?isOneTimeOnly : true);
if(!isOneTimeOnly){
this.appearanceOverride=(modelAttributes!=undefined&&modelAttributes!=""?modelAttributes : undefined);this.wornGarmentOverride=(wornGarments!=undefined&&wornGarments!=""?wornGarments : undefined);
this.requestModelInfo();}else{this.requestModelInfo(undefined,{"appearance":MapUtils.toJSON(modelAttributes),"wornGarments":wornGarments});}}
ModelController.prototype.resetOverride=function(){
this.appearanceOverride=undefined;this.wornGarmentOverride=undefined;}
ModelController.prototype.tryOnItems=function(garmentIds,isAttemptReplace,isReloadModel){
isReloadModel=(isReloadModel!=undefined?isReloadModel : true);
if(garmentIds!=undefined&&garmentIds!=""){
var params=new Array();params["garmentsID"]=garmentIds;params["isAttemptReplace"]=isAttemptReplace!=undefined?isAttemptReplace : false;
if(this.rendererType=="CS"){params["isBestView"]=this.isAutomaticBestView;}else{params["isBestView"]=false;}
this.requestModelInfo("tryOn",params,isReloadModel);
if(isReloadModel){Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_ITEM_TRYON,this);}}}
ModelController.prototype.tryOnExternalItems=function(param1,param2,param3,params,isReloadModel){
isReloadModel=(isReloadModel!=undefined?isReloadModel : true);
if(param1!=undefined&&param1!=""){
params=(params!=undefined?params : new Array());params["param1"]=param1;
if(param2!=undefined){params["param2"]=param2;}
if(param3!=undefined){params["param3"]=param3;}
if(this.rendererType=="CS"){params["isBestView"]=this.isAutomaticBestView;}else{params["isBestView"]=false;}
this.requestModelInfo("tryOn",params,isReloadModel);
if(isReloadModel){Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_ITEM_TRYON,this);}}}
ModelController.prototype.setContent=function(garmentIds,params){
if(garmentIds!=undefined&&garmentIds!=""){
this.requestModelInfo("setContent",{garmentsID:garmentIds,layoutId:this.layoutId});Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_ITEM_TRYON,this);}}
ModelController.prototype.setAppearance=function(modelAttributes,params){
if(typeof(ModelQuestionnaire)!="undefined"){ModelQuestionnaire.setAnswersMap(modelAttributes);}}
ModelController.prototype.setDefaultAppearance=function(){
if(typeof(ModelQuestionnaire)!="undefined"){ModelQuestionnaire.restoreDefaultAnswers();}}
ModelController.prototype.tryOnFavoriteOutfit=function(pOutfitId){
if(pOutfitId!=undefined&&pOutfitId!=""){
this.requestModelInfo("tryOnFavoriteOutfit",{outfitId:pOutfitId,defaultType:"clear"});Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_ITEM_TRYON,this);}}
ModelController.prototype.tryOnOutfit=function(pOutfitId){
if(pOutfitId!=undefined&&pOutfitId!=""){this.requestModelInfo("tryOnOutfit",{outfitId:pOutfitId});Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_ITEM_TRYON,this);}}
ModelController.prototype.tryOnRetailerOutfit=function(pOutfitId){
if(pOutfitId!=undefined&&pOutfitId!=""){this.requestModelInfo("tryOnRetailerOutfit",{outfitId:pOutfitId});Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_ITEM_TRYON,this);}}
ModelController.prototype.removeGarments=function(garmentIds){
if(garmentIds!=undefined&&garmentIds!=""){this.requestModelInfo("removeGarments",{garmentsID:garmentIds});Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_ITEM_REMOVE,this);}}
ModelController.prototype.removeItems=function(itemIds){
if(itemIds!=undefined&&itemIds!=""){this.requestModelInfo("removeItems",{itemsID:itemIds});Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_ITEM_REMOVE,this);}}
ModelController.prototype.rotateLeft=function(){
this.setViewId((parseInt(this.viewId)-1>0?this.viewId-1 : this.viewCount[this.layoutId]),true);}
ModelController.prototype.rotateRight=function(){
this.setViewId(parseInt(this.viewId)+1>this.viewCount[this.layoutId]?1 : parseInt(this.viewId)+1,true);}
ModelController.prototype.setViewId=function(index,isReloadModel){
isReloadModel=(isReloadModel!=undefined?isReloadModel : true);
if(index!=undefined&&index>0&&index<=this.viewCount[this.layoutId]){this.viewId=index;
State.set("viewId",this.viewId);
if(isReloadModel){this.requestModelInfo("modelDisplay");}}}
ModelController.prototype.setCameraPresetId=function(index,isReloadModel){
isReloadModel=(isReloadModel!=undefined?isReloadModel : true);
if(index!=undefined&&index>=0&&index<=this.layoutCameraPresets[this.layoutId].length){this.cameraPresetId=index;
State.set("cameraPresetId",this.viewId);
if(isReloadModel){
CameraControl.executeCameraPreset(this.cameraPresetId);}}}
ModelController.prototype.mouseZoom=function(pMouseLeft,pMouseTop){
var modelElement=document.getElementById(this.imageElementId);
this.zoom(parseInt(pMouseLeft-getAbsLeft(modelElement)),parseInt(pMouseTop-getAbsTop(modelElement)));}
ModelController.prototype.zoom=function(left,top,zoomFactor){
if(!this.isZoomedIn){
zoomFactor=(zoomFactor!=undefined?zoomFactor : this.zoomFactor);
if(typeof(ModelMap)!="undefined"){ModelMap.disable();}
this.isZoomedIn=true;
var x1=(left-(this.imageWidth/zoomFactor)/2);var y1=(top-(this.imageHeight/zoomFactor)/2);var x2=(left+(this.imageWidth/zoomFactor)/2);var y2=(top+(this.imageHeight/zoomFactor)/2);
if(x1<0){x2+=Math.abs(x1);x1=0;}
if(x2>this.imageWidth){x1-=(x2-this.imageWidth);x2=this.imageWidth;}
if(y1<0){y2+=Math.abs(y1);y1=0;}
if(y2>this.imageHeight){y1-=(y2-this.imageHeight);y2=this.imageHeight;}
var CROPx1=x1/this.imageWidth;var CROPy1=1-(y2/this.imageHeight);var CROPx2=x2/this.imageWidth;var CROPy2=1-(y1/this.imageHeight);
this.requestModelInfo(undefined,{"CROPx1":CROPx1,"CROPy1":CROPy1,"CROPx2":CROPx2,"CROPy2":CROPy2});
Anim.scale(
this.imageElementId,left,top,zoomFactor);}}
ModelController.prototype.resetZoom=function(){
if(this.isZoomedIn){
this.isZoomedIn=false;
this.requestModelInfo();
Anim.reset(this.imageElementId);
if(typeof(ModelMap)!="undefined"&&!ModelMap.isEnabled){ModelMap.enable();}}}
ModelController.prototype.undo=function(){
this.requestModelInfo("undo");}
ModelController.prototype.redo=function(){
this.requestModelInfo("redo");}
/**
* Clears the model/scene using rule engine
*/
ModelController.prototype.clear=function(isReloadModel){
var params=new Array();
params["useUndoRedo"]=true;params["defaultType"]="clear";
if(this.drMode!=""&&this.drMode!=undefined){params["drMode"]=this.drMode;}
this.requestModelInfo("removeAll",params,isReloadModel);Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_CLEARED,this);}
ModelController.prototype.reset=function(isReloadModel){
this.putOnDefaultOutfit(isReloadModel);Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_RESET,this);}
ModelController.prototype.putOnDefaultOutfit=function(isReloadModel){
var params=new Array();isReloadModel=(isReloadModel!=undefined?isReloadModel : true);
params["useUndoRedo"]=true;
if(this.defaultOutfit!=undefined&&this.defaultOutfit[Workspace.population]!=undefined&&this.defaultOutfit[Workspace.population]!=""){
params["garmentsID"]=this.defaultOutfit[Workspace.population];this.requestModelInfo("setContent",params,isReloadModel);}else{
if(this.defaultType!=""){params["defaultType"]=this.defaultType;}
else{params["defaultType"]="initial";}
if(this.drMode!=""&&this.drMode!=undefined){params["drMode"]=this.drMode;}
this.requestModelInfo("removeAll",params,isReloadModel);}}
ModelController.prototype.sendRequest=function(pActionType,pParams,handlerUrl){
var requestParams=new Array();
pParams=MapUtils.toArray(pParams);
requestParams=requestParams.concat(pParams);
det.sendRequest({serverUrl:(handlerUrl!=undefined?handlerUrl : this.handlerUrl)+pActionType,action:pActionType,parameters:requestParams,callingController:this,group:"Model"});}
ModelController.prototype.onMouseClick=function(pEvent){}
ModelController.prototype.setBestView=function(garmentId,isMultiInstance,onComplete,focusFactor){
if(garmentId!=undefined&&garmentId.split(",").length==1){
isMultiInstance=isMultiInstance==undefined?false : isMultiInstance;
var item=Items.getItemFromGarmentId(garmentId);var itemPresetId=undefined;
if(item!=undefined&&item["CAMERA_PRESETS"]!=undefined){for(var index in item["CAMERA_PRESETS"]){if(item["CAMERA_PRESETS"][index]["LAYOUT_ID"]==Model.layoutId){itemPresetId=index;break;}}}
if(isMultiInstance){
if(item==undefined){item=Items.garmentMap[garmentId];}
if(item!=undefined&&itemPresetId!=undefined){
log.debug("BEST VIEW: Type: multi instance-camera preset",this);
var cameraPreset=item["CAMERA_PRESETS"][itemPresetId];
var cameraState={"fov":cameraPreset["FOV"],"position":[cameraPreset["POSX"],cameraPreset["POSY"],cameraPreset["POSZ"]],"rotation":[cameraPreset["ROTX"],cameraPreset["ROTY"],cameraPreset["ROTZ"]]}
var cameraTarget={"name":"point","transform":[1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,cameraPreset["TARGETX"],cameraPreset["TARGETY"],cameraPreset["TARGETZ"],1.0]}
this.afterBestViewAction=onComplete;
CameraControl.executeSetCamera(cameraState,cameraTarget);}else{log.debug("BEST VIEW: Type: multi instance-no camera preset: ERROR",this);this.isInstanceSelectionMode=false;log.error("ERROR: No preset found for multi-instance garmentId: "+garmentId);if(Model.isFirstModelDisplay){this.requestModelInfo();}}}
else if(Items.isOutfit(Items.getItemId(garmentId))){
var cameraPreset=undefined;
if(item!=undefined&&itemPresetId!=undefined){
log.debug("BEST VIEW: Type: outfit-camera preset",this);
cameraPreset=item["CAMERA_PRESETS"][itemPresetId];
var cameraState={"fov":cameraPreset["FOV"],"position":[cameraPreset["POSX"],cameraPreset["POSY"],cameraPreset["POSZ"]],"rotation":[cameraPreset["ROTX"],cameraPreset["ROTY"],cameraPreset["ROTZ"]]}
var cameraTarget={"name":"point","transform":[1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,cameraPreset["TARGETX"],cameraPreset["TARGETY"],cameraPreset["TARGETZ"],1.0]}
this.afterBestViewAction=onComplete;
CameraControl.executeSetCamera(cameraState,cameraTarget);}
else{log.debug("BEST VIEW: Type: outfit-no camera preset,set to preset #0 of current layout",this);
CameraControl.executeCameraPreset(0);}
}
else if(Items.isSet(Items.getItemId(garmentId))){
log.debug("BEST VIEW: Set with preset",this);
if(item["CAMERA_PRESETS"]!=undefined&&item["CAMERA_PRESETS"][itemPresetId]!=undefined){
var cameraPreset=item["CAMERA_PRESETS"][itemPresetId];
var cameraState={"fov":cameraPreset["FOV"],"position":[cameraPreset["POSX"],cameraPreset["POSY"],cameraPreset["POSZ"]],"rotation":[cameraPreset["ROTX"],cameraPreset["ROTY"],cameraPreset["ROTZ"]]}
var cameraTarget={"geometryName":"point","transform":[1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,cameraPreset["TARGETX"],cameraPreset["TARGETY"],cameraPreset["TARGETZ"],1.0]}
CameraControl.executeSetCamera(cameraState,cameraTarget);Model.camera.focusGarmentId=garmentId;}else{log.error("No preset for set,garmentId="+garmentId,this);}
}else{
if(item!=undefined&&itemPresetId!=undefined&&item["CAMERA_PRESETS"][itemPresetId]["TARGETX"]==undefined){
var cameraPreset=item["CAMERA_PRESETS"][itemPresetId];
var cameraState={"fov":cameraPreset["FOV"],"position":[cameraPreset["POSX"],cameraPreset["POSY"],cameraPreset["POSZ"]],"rotation":[cameraPreset["ROTX"],cameraPreset["ROTY"],cameraPreset["ROTZ"]]}
log.debug("BEST VIEW: Type: single instance with camera preset",this);
CameraControl.executeItemPreset(garmentId,cameraState);
}else{
log.debug("BEST VIEW: Type: single instance-calculated view",this);
if(garmentId.indexOf(":")==-1){for(var index in this.content.allGarmentsArray){if(this.content.allGarmentsArray[index].indexOf(garmentId)>-1){garmentId=this.content.allGarmentsArray[index];break;}}}
CameraControl.focusOnGarment(garmentId,focusFactor);}}
}else{
log.debug("BEST VIEW: Type: multiple garments passed,using preset #0",this);CameraControl.executeCameraPreset(0);}}
ModelController.prototype.onMouseDown=function(pEvent){
var isEventHandled=false;var mouse=getMouseState(pEvent);var modelElement=document.getElementById(this.imageElementId);var pX=parseInt(mouse.left-getAbsLeft(modelElement));var pY=parseInt(mouse.top-getAbsTop(modelElement));
if(!isEventHandled&&!this.isEnlarged&&!this.isZoomedIn&&this.isZoomFeatureEnabled&&!this.isInstanceSelectionMode&&mouse.button==1){this.mouseZoom(mouse.left,mouse.top);}
if(typeof(ModelMap)!="undefined"){
if(this.isInstanceSelectionMode){
var polygonInfo=ModelMap.getPolygonInfoFromCoordinate(pX,pY);
if(polygonInfo!=undefined){
this.selectInstance(polygonInfo["key"]);}else{this.disableInstanceSelectionMode();}
}else{
var garmentId="";
if(!this.isZoomFeatureEnabled&&ModelMap!=undefined){
garmentId=ModelMap.getGarmentIdFromCoordinate(pX,pY);
if(garmentId!=undefined&&!this.isZoomedIn){
if(this.rendererType=="RT3D"){this.setBestView(garmentId,undefined,undefined);}
if(this.mouseOverActionThread!=undefined){clearTimeout(this.mouseOverActionThread);this.mouseOverActionThread=undefined;}
Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_ITEM_MOUSEDOWN,{"garmentId":garmentId});}else{
ModelMap.resetItemHighlight();this.isOverPolygon=false;
}
}
}}
Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_ONMOUSECLICK,this);}
ModelController.prototype.onMouseOver=function(pEvent){
if(!this.isInstanceSelectionMode){
var mouse=getMouseState(pEvent);
if(this.mouseOverActionThread!=undefined){clearTimeout(this.mouseOverActionThread);this.mouseOverActionThread=undefined;}
this.mouseOverActionThread=setTimeout(this.id+".onMouseOverAction("+mouse.left+","+mouse.top+")",500);
if(typeof(ModelMap)!="undefined"){ModelMap.updateMousePointer(mouse.left,mouse.top);}}}
ModelController.prototype.onMouseOverAction=function(mouseX,mouseY){
if(typeof(ModelMap)!="undefined"){
if(this.mouseOverActionThread!=undefined){clearTimeout(this.mouseOverActionThread);this.mouseOverActionThread=undefined;}
var modelElement=document.getElementById(this.imageElementId);
if(modelElement!=undefined&&!this.isInstanceSelectionMode&&!this.isEnlarged){
mouseY=parseInt(mouseY-getAbsTop(modelElement));mouseX=parseInt(mouseX-getAbsLeft(modelElement));}}
Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_ONMOUSEOVER,{"mouseX":mouseX,"mouseY":mouseY});}
ModelController.prototype.onMouseUp=function(pEvent){
this.resetZoom();}
ModelController.prototype.onMouseOut=function(pEvent){
this.resetZoom();}
ModelController.prototype.enableInstanceSelectionMode=function(instancesInfo){
if(instancesInfo!=undefined){
Workspace.events.throwEvent(Workspace.events.EVENT_INSTANCE_SELECTION_START,this);
this.isInstanceSelectionMode=true;
this.instancesInfo=instancesInfo;
for(var garmentId in instancesInfo){
if(this.instancesInfo[garmentId]["CSURL"]!=""){
if(this.rendererType=="CS"){ModelMap.loadMap(this.getUpdatedCompositorImageUrl(this.instancesInfo[garmentId]["CSURL"]));}else{ModelMap.loadMap(this.getUpdatedMPSImageUrl(this.instancesInfo[garmentId]["CSURL"]));}
}
break;}
Workspace.hideWait();
this.garmentInstanceSelectionInfo=undefined;}}
ModelController.prototype.disableInstanceSelectionMode=function(isLoadMap){
isLoadMap=isLoadMap==undefined?true : isLoadMap;
if(this.isInstanceSelectionMode){this.isInstanceSelectionMode=false;
Workspace.events.throwEvent(Workspace.events.EVENT_INSTANCE_SELECTION_STOPPED,this);
this.instancesInfo=undefined;
if(document.getElementById("modelDimmer")!=undefined){Anim.hide("modelDimmer");}
if(document.getElementById("selectInstance")!=undefined){Anim.hide("selectInstance");}
Anim.stopPulse("itemOutliner");
if(typeof(ModelMap)!="undefined"&&isLoadMap){ModelMap.resetItemHighlight();
}}}
ModelController.prototype.displayInstanceSelection=function(){
if(typeof(ModelMap)!="undefined"){
if(MapUtils.getCount(ModelMap.allPolygons)>1){
if(document.getElementById("modelDimmer")!=undefined){Anim.show("modelDimmer");}
if(document.getElementById("selectInstance")!=undefined){Anim.show("selectInstance");}
Anim.startPulse("itemOutliner",20,80,1000);
ModelMap.showAllPolygons();
}else{this.selectInstance(MapUtils.getKeyAtIndex(0,ModelMap.allPolygons))}}}
ModelController.prototype.selectInstance=function(key){
var isMatch=false;var instanceTemp="";
for(var garmentId in this.instancesInfo){
for(var instanceIndex in this.instancesInfo[garmentId]["INSTANCES"]){
instanceTemp=this.instancesInfo[garmentId]["INSTANCES"][instanceIndex]
var matchFound=false;
if(this.rendererType=="CS"){if(this.instancesInfo[garmentId]["INSTANCES"][instanceIndex]["OUTLINE_KEY"]==key){matchFound=true;}}
else{matchFound=this.compareKeys(this.instancesInfo[garmentId]["INSTANCES"][instanceIndex]["OUTLINE_KEY"],key);}
if(matchFound){
instanceId=this.instancesInfo[garmentId]["INSTANCES"][instanceIndex]["INSTANCE_ID"];isMatch=true;
if(this.garmentIdToMove!=undefined){this.moveGarment(this.garmentIdToMove,garmentId+":"+instanceId);this.garmentIdToMove=undefined;
}else{this.tryOnItems(garmentId+":"+instanceId);}
break;}}
if(isMatch){break;}}
this.disableInstanceSelectionMode(true);}
ModelController.prototype.compareKeys=function(key1,key2){
var mapKey1=key1.split("_");var mapKey2=key2.split("_");
if(mapKey1[0]!=mapKey2[0]){return false;}
if(mapKey1[1]!=mapKey2[1]){return false;}
if(Math.abs(parseFloat(mapKey1[mapKey1.length-4])-parseFloat(mapKey2[mapKey2.length-4]))>0.1){return false;}
if(Math.abs(parseFloat(mapKey1[mapKey1.length-3])-parseFloat(mapKey2[mapKey2.length-3]))>0.1){return false;}
if(Math.abs(parseFloat(mapKey1[mapKey1.length-2])-parseFloat(mapKey2[mapKey2.length-2]))>0.1){return false;}
return true;}
ModelController.prototype.zoomToItem=function(itemId){
if(typeof(ModelMap)!="undefined"){
var coordinates=new Array();
for(key in ModelMap.mapArray[parseInt(itemId)]["polygons"]){coordinates=ModelMap.getBoundingBox(ModelMap.mapArray[parseInt(itemId)]["polygons"][key]);break;}
Anim.scale(
this.imageElementId,(coordinates[2])/2+coordinates[0],(coordinates[3])/2+coordinates[1],2);}}
ModelController.prototype.setSize=function(width,height,isQuickMode){
quickMode=(isQuickMode!=undefined&&isQuickMode==true?true : false);
var modelElement=document.getElementById(this.imageElementId);
if(modelElement!=undefined){
if(quickMode){modelElement.style.width=width+"px";modelElement.style.height=height+"px";}else{
var attributes=new Array();attributes["sWidth"]=parseInt(modelElement.style.width);attributes["sHeight"]=parseInt(modelElement.style.height);attributes["tWidth"]=width;attributes["tHeight"]=height;
Anim.animateElement(this.imageElementId,attributes);}
this.requestModelInfo();}}
ModelController.prototype.enlarge=function(isQuickMode){
if(!this.isZoomedIn){
quickMode=(isQuickMode!=undefined&&isQuickMode==true);this.isEnlarged=true;this.setSize(this.largeImageWidth,this.largeImageHeight,quickMode);
Anim.openSingle("modelContainer",quickMode);}}
ModelController.prototype.resetEnlarge=function(isQuickMode){
if(!this.isZoomedIn){quickMode=(isQuickMode!=undefined&&isQuickMode);this.isEnlarged=false;this.setSize(this.imageWidth,this.imageHeight,quickMode);
Anim.reset("modelContainer",quickMode);}}
ModelController.prototype.setLayout=function(index,isReloadModel){
isReloadModel=(isReloadModel!=undefined?isReloadModel : true);
if(this.layoutIdArray[index]!=undefined){this.layoutId=this.layoutIdArray[index];}else{this.layoutId=this.layoutIdArray[0];}
if(this.rendererType=="CS"){this.setViewId(1,false);}
else{this.cameraPresetId=0;}
State.set("layoutIndex",index);
if(this.layoutSettings!=undefined){if(this.layoutSettings[this.layoutId]!=undefined&&this.camera!=undefined){this.camera.setBoundingBox(this.layoutSettings[this.layoutId]["boundingBox"]);this.camera.setTransitionPoint(this.layoutSettings[this.layoutId]["transitionPoint"]);this.camera.setLighting(this.layoutSettings[this.layoutId]["lighting"]);}}
if(this.layoutCameraPresets!=undefined){if(this.layoutCameraPresets[this.layoutId][0]!=undefined&&this.camera!=undefined){this.camera.setFocusGeometry(this.layoutCameraPresets[this.layoutId][0]["target"]["name"],this.layoutCameraPresets[this.layoutId][0]["target"]["transform"]);this.camera.setCameraAction(this.layoutCameraPresets[this.layoutId][0]["state"]);}}
if(isReloadModel){
var params=new Array();if(this.defaultType!=""){params["defaultType"]=this.defaultType;}
if(this.drMode!=""&&this.drMode!=undefined){params["drMode"]=this.drMode;}
this.requestModelInfo("removeAll",params);}
Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_LAYOUT_CHANGED,this);}
ModelController.prototype.setLayoutId=function(layoutId,isReloadModel){
isReloadModel=(isReloadModel==undefined?true : isReloadModel);
if(this.layoutId!=layoutId){
for(var index in this.layoutIdArray){
if(this.layoutIdArray[index]==layoutId){this.setLayout(index,isReloadModel);break;}}}}
ModelController.prototype.showItemMoveToLocations=function(garmentId,instanceId){
this.garmentIdToMove=garmentId+":"+instanceId;this.tryOnItems(garmentId);}
ModelController.prototype.moveGarment=function(fromGarmentId,toGarmentId){
if(fromGarmentId!=undefined&&fromGarmentId!=""&&toGarmentId!=undefined&&toGarmentId!=""){
this.requestModelInfo(
"move",{"originGarmentID":fromGarmentId,"destinationGarmentID":toGarmentId});}}
ModelController.prototype.showModelWithoutItems=function(){
this.isDefaultWear=true;this.requestModelInfo();}
ModelController.prototype.showModelWithItems=function(){
this.isDefaultWear=false;this.requestModelInfo();}
ModelController.prototype.handleResponseImage=function(attributes){
var finalImageUrl="";
if(attributes.response["remsinfo.current.layoutid"]!=undefined){
if(this.layoutId!=attributes.response["remsinfo.current.layoutid"]){this.layoutId=attributes.response["remsinfo.current.layoutid"];Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_LAYOUT_CHANGED,this);}}
if(attributes.response["image"]!=undefined&&attributes.response["image"]["VMImage"]!=undefined&&attributes.response["image"]["VMImage"]!=""){
this.VMContext=attributes.response["image"]["VMImage"];
if(this.rendererType=="CS"){
finalImageUrl=this.getUpdatedCompositorImageUrl(attributes.response["image"]["VMImage"]);
if(attributes.response["availableInstancesInfo"]!=undefined){this.garmentInstanceSelectionInfo=attributes.response["availableInstancesInfo"];}
this.updateImage(
finalImageUrl,attributes.parametersMap["imageElementId"]);}else{finalImageUrl=this.getUpdatedMPSImageUrl(attributes.response["image"]["VMImage"]);}
if(attributes.response["availableInstancesInfo"]==undefined&&this.rendererType=="RT3D"){
if(attributes.action!="tryOn"||this.isFirstModelDisplay){
if(this.isFirstModelDisplay&&attributes.action=="tryOn"){
if(attributes.response.addedGarmentidList!=undefined&&
attributes.response.addedGarmentidList[0]!=undefined){
Workspace.events.throwEvent(Workspace.events.EVENT_CONTROLLER_INITIALIZED,this);
loopUntil("typeof(ModelMap)=='object'",escape(this.id+".setBestView('"+attributes.response.addedGarmentidList[0]+"',false,undefined);"));}else{this.updateImage(
finalImageUrl,attributes.parametersMap["imageElementId"]);}}else{this.updateImage(
finalImageUrl,attributes.parametersMap["imageElementId"]);}}}}
if(attributes.response["result"]!=undefined){this.camera.update(attributes.response["result"]);}
if(attributes.response["viewId"]!=undefined&&attributes.parametersMap["imageElementId"]==undefined){this.setViewId(parseInt(attributes.response["viewId"]),false);}
return finalImageUrl;}
ModelController.prototype.handleResponseMultiInstance=function(attributes,finalImageUrl){
if(attributes.response["availableInstancesInfo"]!=undefined&&!this.isInstanceSelectionMode){
if(Workspace.isControllerInitialized("ModelMap")&&!Model.isFirstModelDisplay){
if(this.rendererType=="RT3D"){
this.garmentInstanceSelectionInfo=attributes.response["availableInstancesInfo"];this.isInstanceSelectionMode=true;this.setBestView(attributes.parametersMap["garmentsID"],true,this.id+".enableInstanceSelectionMode("+this.id+".garmentInstanceSelectionInfo)");}else{
this.garmentInstanceSelectionInfo=attributes.response["availableInstancesInfo"];}
}else if(this.isFirstModelDisplay&&attributes.parametersMap["param1"]!=undefined){
if(this.rendererType=="RT3D"){
Workspace.events.throwEvent(Workspace.events.EVENT_CONTROLLER_INITIALIZED,this);
this.garmentInstanceSelectionInfo=attributes.response["availableInstancesInfo"];
var garmentIdFromInstance=undefined;for(index in this.garmentInstanceSelectionInfo){garmentIdFromInstance=index;}
this.isInstanceSelectionMode=true;
loopUntil("typeof(ModelMap)=='object'",escape(this.id+".setBestView('"+garmentIdFromInstance+"',true,\""+this.id+".enableInstanceSelectionMode("+this.id+".garmentInstanceSelectionInfo);\");"));}else{
if(Workspace.isControllerInitialized("ModelMap")){this.enableInstanceSelectionMode(attributes.response["availableInstancesInfo"]);}
else{this.garmentInstanceSelectionInfo=attributes.response["availableInstancesInfo"];}}
}else{
if(this.isInstanceSelectionMode){this.garmentInstanceSelectionInfo=attributes.response["availableInstancesInfo"];}}
if(attributes.callingController==this&&(attributes.response["errorCode"]!=undefined||attributes.isInvalidServerResponse)){this.displayInstanceSelection();}}}
ModelController.prototype.handleResponseErrors=function(attributes){
if(attributes.response["bodysets"]!=undefined&&attributes.parametersMap["imageElementId"]==undefined&&!MapUtils.isArrayContentEquals(this.bodySet,attributes.response["bodysets"])){
this.bodySet=attributes.response["bodysets"];
Workspace.events.throwEvent(Workspace.events.EVENT_BODYSET_CHANGED,this);}
if(attributes.callingController==this&&attributes.parametersMap["param1"]!=undefined){
if(attributes.response["itemsInfo"]!=undefined){for(key in attributes.response["itemsInfo"]){this.lastExternalTryOnGarmentId=key;break;}}
if(Workspace.query.param1!=undefined&&
attributes.response["clientDataMapping"]!=undefined&&
attributes.response["clientDataMapping"][Workspace.query.param1.split(",")[0]]!=undefined){
this.lastExternalTryOnGarmentId=attributes.response["clientDataMapping"][Workspace.query.param1.split(",")[0]];}}}
ModelController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED){if(attributes!=undefined&&attributes.response!=undefined){
var finalImageUrl=this.handleResponseImage(attributes);this.handleResponseMultiInstance(attributes,finalImageUrl);this.handleResponseErrors(attributes);}
}else if(eventKey==Workspace.events.EVENT_CONTROLLER_INITIALIZED){
if(this.garmentInstanceSelectionInfo!=undefined&&Workspace.isControllerInitialized("ModelMap")){
if(!this.isInstanceSelectionMode){this.enableInstanceSelectionMode(this.garmentInstanceSelectionInfo);this.garmentInstanceSelectionInfo=undefined;}}
}else if(eventKey==Workspace.events.EVENT_MODEL_IMAGE_CHANGED){if(this.garmentInstanceSelectionInfo!=undefined){if(typeof(ModelMap)!="undefined"){this.enableInstanceSelectionMode(this.garmentInstanceSelectionInfo);}else{loopUntil("typeof(ModelMap)=='object'",escape(this.id+".enableInstanceSelectionMode("+this.id+".garmentInstanceSelectionInfo);"));}}
}else if(eventKey==Workspace.events.EVENT_MODEL_ATTRIBUTES_CHANGED&&this.isInitialized){this.requestModelInfo();
}else if(eventKey==Workspace.events.EVENT_MODEL_MAP_LOADED&&this.isInstanceSelectionMode){this.displayInstanceSelection();}else if(eventKey==Workspace.events.EVENT_USER_SIGNIN){this.requestModelInfo();}else if(eventKey==Workspace.events.EVENT_USER_SIGNOUT){
this.setDefaultAppearance();this.requestModelInfo();}}
ModelController.prototype.isBodySetMatched=function(resServerBodySet){
var isBodysetMatch=false;
currentModelBodySet=this.bodySet;
if(currentModelBodySet!=undefined &&resServerBodySet!=undefined &&resServerBodySet.length>0&&currentModelBodySet.length>0){
currentModelBodySet=currentModelBodySet.sort();resServerBodySet=resServerBodySet.sort();
for(var i=0;i<currentModelBodySet.length;i++){for(var j=0;j<resServerBodySet.length;j++){if(currentModelBodySet[i]==resServerBodySet[j]){isBodysetMatch=true;break;break;}}}}else{isBodysetMatch=true;}
return isBodysetMatch;}
function ModelViewController(id){
this.id=id;}
ModelViewController.prototype.id="ModelViewController";ModelViewController.prototype.elementId="";ModelViewController.prototype.containerElementId="";ModelViewController.prototype.templateElementId="";ModelViewController.prototype.viewCount=undefined;ModelViewController.prototype.isInitialized=false;ModelViewController.prototype.labels=undefined;
ModelViewController.prototype.init=function(){
this.elementId=this.id+"Panel";this.containerElementId=this.id+"Container";this.templateElementId=this.id+"Template";
resource.applyProperties(this.id+"Properties",this);
this.viewCount=resource.get("ModelProperties/viewCount");this.isInitialized=true;}
ModelViewController.prototype.update=function(stateAttributes){
if(Model.rendererType=="CS"){ParserUtils.applyTemplate(this.templateElementId,this.containerElementId,stateAttributes);}
else{ParserUtils.applyTemplate(this.id+"MPSTemplate",this.containerElementId,stateAttributes);}}
ModelViewController.prototype.setViewId=function(index){
Model.setViewId(parseInt(index));
this.hide();}
ModelViewController.prototype.setCameraPresetId=function(index){
CameraControl.setCameraPreset(parseInt(index));
this.hide();}
ModelViewController.prototype.isVisible=function(){
return document.getElementById(this.elementId).style.display=="block";}
ModelViewController.prototype.show=function(){
Workspace.events.addListener(Workspace.events.EVENT_MODEL_IMAGE_CHANGED,this);Workspace.events.addListener(Workspace.events.EVENT_MODEL_ONMOUSEOVER,this);
this.update(Model);
}
ModelViewController.prototype.hide=function(){
Anim.reset(this.elementId);}
ModelViewController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_MODEL_IMAGE_CHANGED){
if(Model.rendererType=="CS"){this.update(attributes);}
else{this.update(Model);}
}else if(eventKey==Workspace.events.EVENT_MODEL_ONMOUSEOVER&&this.isVisible()){this.hide();}
}
function Camera(id){
this.id=id;}
Camera.prototype.id="Camera";Camera.prototype.isInitialized=false;Camera.prototype.action=undefined;Camera.prototype.state=undefined;Camera.prototype.focusGeometry=undefined;Camera.prototype.focusGarmentId=undefined;Camera.prototype.boundingBox=undefined;Camera.prototype.lighting=undefined;Camera.prototype.transitionPoint=undefined;Camera.prototype.navigation=undefined;Camera.prototype.isReturnCamera=true;Camera.prototype.isReturnOutlines=true;Camera.prototype.isReturnNavigation=true;Camera.prototype.maxVerticalPosition=155;Camera.prototype.maxVerticalAngle=0;Camera.prototype.orbitTolerance=0.3;Camera.prototype.ratioTolerance=0.1;
Camera.prototype.init=function(){
this.boundingBox=undefined;this.action=undefined;this.lighting=undefined;this.isInitialized=true;}
Camera.prototype.update=function(infoMap){
if(infoMap!=undefined&&infoMap["cameraInfo"]!=undefined){
this.action=undefined;this.state.position=eval("["+infoMap["cameraInfo"][0]["position"][0]+"]");this.state.rotation=eval("["+infoMap["cameraInfo"][0]["rotation"][0]+"]");this.state.fov=infoMap["cameraInfo"][0]["fov"][0];this.navigation=(infoMap["navigation"]!=undefined?infoMap["navigation"][0] : undefined);
if(infoMap["target"]!=undefined){var newTransform=infoMap["target"][0]["transform"][0].split(",");this.setFocusGeometry(infoMap["target"][0]["geometryName"][0],newTransform,"");}
log.debug("Model.camera has been updated from MPS with: "+this.getMPSStateString(),this);Workspace.events.throwEvent(Workspace.events.EVENT_CAMERA_CHANGED,this);}}
Camera.prototype.setCameraFrom=function(newCamera,isIncludeId){
if(newCamera.state!=undefined){this.state=MapUtils.putAll(this.state,newCamera.state);}
if(newCamera.action!=undefined){this.action=MapUtils.putAll(this.action,newCamera.action);}
if(newCamera.transitionPoint!=undefined){this.transitionPoint=MapUtils.putAll(this.transitionPoint,newCamera.transitionPoint);}
if(newCamera.lighting!=undefined){this.lighting=newCamera.lighting;}
if(newCamera.boundingBox!=undefined){this.boundingBox=MapUtils.putAll(this.boundingBox,newCamera.boundingBox);}
if(newCamera.focusGeometry!=undefined){this.focusGeometry=MapUtils.putAll(this.focusGeometry,newCamera.focusGeometry);}
if(newCamera.focusGarmentId!=undefined){this.focusGarmentId=newCamera.focusGarmentId;}
if(newCamera.navigation!=undefined){this.navigation=newCamera.navigation;}
if(isIncludeId==true){this.id=newCamera.id;}
}
Camera.prototype.setFocusGeometry=function(name,transform,garmentId){
this.focusGeometry={"name":name,"transform":MapUtils.getClone(transform)}
if(garmentId!=undefined){this.focusGarmentId=garmentId;}}
Camera.prototype.setLighting=function(name){
this.lighting=name;}
Camera.prototype.setBoundingBox=function(boundingBox){
this.boundingBox=MapUtils.getClone(boundingBox);}
Camera.prototype.setTransitionPoint=function(transitionPoint){
this.transitionPoint=MapUtils.getClone(transitionPoint);}
Camera.prototype.setPlaneOrbitAction=function(angle,ratio){
if(this.navigation!=undefined&&Model.camera.navigation["orbit"][0]["angle"]!=undefined&&Model.camera.navigation["orbit"][0]["ratio"]!=undefined){
for(exludedZoneIndex in Model.camera.navigation["orbit"][0]["angle"][0]["exclude"]){
if(angle>0){
lowerValue=Model.camera.navigation["orbit"][0]["angle"][0]["exclude"][exludedZoneIndex]["lower"][0];
if(lowerValue>0){if(angle>lowerValue){angle=lowerValue;break;}}
}else{
upperValue=Model.camera.navigation["orbit"][0]["angle"][0]["exclude"][exludedZoneIndex]["upper"][0];
if(upperValue<0){if(angle<upperValue){angle=upperValue;break;}}}}
for(exludedZoneIndex in Model.camera.navigation["orbit"][0]["ratio"][0]["exclude"]){
if(ratio>1){
lowerValue=Model.camera.navigation["orbit"][0]["ratio"][0]["exclude"][exludedZoneIndex]["lower"][0];
if(lowerValue>1){if(ratio>lowerValue){ratio=lowerValue;break;}}}else{
lowerValue=Model.camera.navigation["orbit"][0]["ratio"][0]["exclude"][exludedZoneIndex]["lower"][0];
if(lowerValue>1){if(ratio>lowerValue){ratio=lowerValue;break;}}}}}
this.action={"name" : "orbit","angle" : angle,"ratio" : ratio}}
Camera.prototype.isPlaneOrbitActionAllowed=function(angle,ratio){
var result=false;
if(this.navigation!=undefined&&this.navigation["orbit"][0]["angle"]!=undefined){
result=true;
var excludeAngleInfo=this.navigation["orbit"][0]["angle"][0]["exclude"];var excludeRatioInfo=this.navigation["orbit"][0]["ratio"][0]["exclude"];
for(var i in excludeAngleInfo){
if(excludeAngleInfo[i]["lower"][0]<0&&(angle<=excludeAngleInfo[i]["upper"][0]&&angle>=excludeAngleInfo[i]["lower"][0])&&(excludeAngleInfo[i]["upper"][0] / angle<this.orbitTolerance)){
result=false;break;}else if(excludeAngleInfo[i]["upper"][0]>0&&(angle<=excludeAngleInfo[i]["upper"][0]&&angle>=excludeAngleInfo[i]["lower"][0])&&(excludeAngleInfo[i]["lower"][0] / angle<this.orbitTolerance)){
result=false;break;}}
if(result){
for(var i in excludeRatioInfo){
if(excludeRatioInfo[i]["lower"][0]=="INF"){excludeRatioInfo[i]["lower"][0]=9999;}
if(excludeRatioInfo[i]["upper"][0]=="INF"){excludeRatioInfo[i]["upper"][0]=9999;}
if((excludeRatioInfo[i]["upper"][0]<=1&&ratio<1&&(ratio<=excludeRatioInfo[i]["upper"][0]&&ratio>=excludeRatioInfo[i]["lower"][0]))&&((1-(ratio / excludeRatioInfo[i]["upper"][0]))>this.ratioTolerance)){
result=false;break;}else if((excludeRatioInfo[i]["lower"][0]>=1&&ratio>1&&(ratio<=excludeRatioInfo[i]["upper"][0]&&ratio>=excludeRatioInfo[i]["lower"][0]))&&((1-(excludeRatioInfo[i]["lower"][0] / ratio))>this.ratioTolerance)){
result=false;break;}}}
log.debug("testing navigation angle:"+angle+",ratio:"+ratio+" on angle:"+MapUtils.toJSON(excludeAngleInfo)+",ratio:"+MapUtils.toJSON(excludeRatioInfo)+" : "+result,this);}else{
result=true;}
return result;}
Camera.prototype.setFocusAction=function(factor){
this.action={"name" : "focus","factor" : factor}}
Camera.prototype.setRotateAction=function(angle,verticalPosition,verticalAngle){
this.action={"name" : "rotate","horizontalAngle" : angle,"maxVerticalPosition":this.maxVerticalPosition,"vPosition":verticalPosition,"maxVerticalAngle":this.maxVerticalAngle,"vAngle":verticalAngle}}
Camera.prototype.setCameraAction=function(newState){
this.action={"name" : "setCamera","camera" : MapUtils.getClone(newState)}}
Camera.prototype.getMPSString=function(){var random=(Math.random()*10000)+"";random=random.substring(0,random.indexOf("."));
return this.getMPSStateString()+"&"+this.getMPSActionString()+"&"+this.getMPSBoundingBoxString()+"&l="+this.lighting+"&x="+Model.world+"&rand="+random;}
Camera.prototype.getMPSStateString=function(){
var mpsStateString="";
if(this.state!=undefined){
mpsStateString+=
"c="+this.state["position"][0]+";"+this.state["position"][1]+";"+this.state["position"][2]+";"+
this.state["rotation"][0]+";"+this.state["rotation"][1]+";"+this.state["rotation"][2]+";"+
this.state["fov"];
return mpsStateString;}else{return "";}}
Camera.prototype.getMPSActionString=function(){
var mpsActionString="";
if(this.action!=undefined){
if(this.action["name"]=="focus"){
mpsActionString+="a=f";
mpsActionString+="&f.g="+this.getMPSFocusGeometryString();mpsActionString+="&f.f="+this.action["factor"];
if(this.useTransitionPoint){mpsActionString+="&f.p="+this.getMPSTransitionPointString();}
}else if(this.action["name"]=="orbit"){
mpsActionString+="a=o";
mpsActionString+="&o.g="+this.getMPSFocusGeometryString();mpsActionString+="&o.a="+this.action["angle"];mpsActionString+="&o.r="+this.action["ratio"];}else if (this.action["name"]=="setCamera"){
mpsActionString+="a=p";
mpsActionString+="&p.c="+this.action["camera"]["position"][0]+";"+this.action["camera"]["position"][1]+";"+this.action["camera"]["position"][2]+";"+
this.action["camera"]["rotation"][0]+";"+this.action["camera"]["rotation"][1]+";"+this.action["camera"]["rotation"][2]+";" +
this.action["camera"]["fov"];}else if(this.action["name"]=="rotate"){
mpsActionString+="a=r";
mpsActionString+="&r.y="+this.action["horizontalAngle"];mpsActionString+="&r.p="+this.action["maxVerticalPosition"]+";"+this.action["vPosition"];mpsActionString+="&r.v="+this.action["maxVerticalAngle"]+";"+this.action["vAngle"];}
return mpsActionString;}else{return "a=0";}}
Camera.prototype.getMPSFocusGeometryString=function(){
var mpsGeoString="";
if(this.focusGeometry!=undefined){
mpsGeoString+=this.focusGeometry["name"];
for(var i=0;i<16;i++){if(i!=3&&i!=7&&i!=11&&i!=15)
mpsGeoString+=";"+(Math.round(this.focusGeometry["transform"][i] * 1000.0))/ 1000.0;}
return mpsGeoString;}else{return "";}}
Camera.prototype.getMPSBoundingBoxString=function(){
var mpsbbString="";
if(this.boundingBox!=undefined){
mpsbbString+="b="+this.boundingBox["minX"]+";"+this.boundingBox["minY"]+";"+this.boundingBox["minZ"]+";";mpsbbString+=this.boundingBox["maxX"]+";"+this.boundingBox["maxY"]+";"+this.boundingBox["maxZ"];
return mpsbbString;}else{return "";}}
Camera.prototype.getMPSTransitionPointString=function(){
var mpstpString="";
if(this.focusGeometry!=undefined){
mpstpString+=this.transitionPoint[0]+";"+this.transitionPoint[1]+";"+this.transitionPoint[2];
return mpstpString;}else{return "";}}
Camera.prototype.getMPSDataString=function(isReturnCamera,isReturnOutlines,isReturnNavigation){
var parameterList=new Array();
if(isReturnCamera!=undefined?isReturnCamera : this.isReturnCamera){parameterList.push("c");}
if(isReturnOutlines!=undefined?isReturnOutlines : this.isReturnOutlines){parameterList.push("r");}
if(isReturnNavigation!=undefined?isReturnNavigation : this.isReturnNavigation){parameterList.push("n");}
if(this.action!=undefined&&this.action["name"]=="rotate"){parameterList.push("t");}
if(parameterList.length>0){return "&d="+parameterList.join(";");}else{return "";}}
function CameraController(id){
this.id=id;}
CameraController.prototype.id="CameraController";CameraController.prototype.isInitialized=false;CameraController.prototype.presetCount=0;CameraController.prototype.defaultFocusFactor=0.5;
CameraController.prototype.init=function(){
resource.applyProperties(this.id+"Properties",this);this.isInitialized=true;}
CameraController.prototype.executeCameraPreset=function(presetId){
Model.camera.state=MapUtils.getClone(Model.layoutCameraPresets[Model.layoutId][presetId]["state"]);Model.camera.focusGeometry=MapUtils.getClone(Model.layoutCameraPresets[Model.layoutId][presetId]["target"]);Model.camera.setFocusAction(0);log.debug("changing layout preset for : "+Model.layoutId+":"+presetId,this);
this.executeCamera(Model.camera);}
CameraController.prototype.setCameraPresetState=function(camera,presetId,layoutId){
camera.state=MapUtils.getClone(Model.layoutCameraPresets[layoutId][presetId]["state"]);camera.setCameraAction(camera.state);camera.focusGeometry=MapUtils.getClone(Model.layoutCameraPresets[layoutId][presetId]["target"]);}
CameraController.prototype.resetCamera=function(){
var newPosition=Model.layoutSettings[Model.layoutId]["resetViewPosition"];
if(newPosition!=undefined){Model.camera.setFocusAction(0);Model.camera.state.position=MapUtils.getClone(newPosition);this.executeCamera(Model.camera);}}
CameraController.prototype.executeItemPreset=function(garmentId,cameraState){
var garmentData=undefined;
if(Model.content.allGarmentsData[garmentId]==undefined){var instance=Model.content.onMyModelArray["instancesPerGarment"][garmentId];garmentData=Model.content.allGarmentsData[garmentId+":"+instance];}else{garmentData=Model.content.allGarmentsData[garmentId];}
if(garmentData!=undefined){Model.camera.setCameraAction(cameraState);Model.camera.setFocusGeometry(garmentData["geometryName"],garmentData["transform"],garmentId);log.debug("setting preset for garment : "+garmentId,this);this.executeCamera(Model.camera);}}
CameraController.prototype.executeSetCamera=function(cameraState,cameraTarget){
Model.camera.setCameraAction(cameraState);Model.camera.setFocusGeometry(cameraTarget["geometryName"],cameraTarget["transform"]);log.debug("setting predefined camera and executing it",this);this.executeCamera(Model.camera);}
CameraController.prototype.executeCamera=function(camera){
if(camera==undefined){log.error("Cannot execute camera,it is null!");}else{var imageUrl=Model.VMContext+"&"+camera.getMPSString()+"&m=r";log.debug("Executing camera with :"+imageUrl,this);Model.updateImage(imageUrl);}}
CameraController.prototype.viewInContext=function(garmentId){
garmentId=(garmentId==undefined?Model.camera.focusGarmentId : garmentId);
if(garmentId!=undefined){
if(!Items.isSet(Items.getItemId(garmentId))){
this.focusOnGarment(garmentId,0.25,true);}else{
log.error("Garment: "+garmentId+" is a set and cannot do a view in context");}}}
CameraController.prototype.focusOnGarment=function(garmentId,factor,isTransitionPointUsed){
this.isTransitionPointUsed=isTransitionPointUsed==undefined?false : isTransitionPointUsed;factor=factor==undefined?this.defaultFocusFactor : factor;
if(garmentId!=undefined){
if (Model.content.allGarmentsData[garmentId]!=undefined){
Model.camera.setFocusAction(factor);
if(isTransitionPointUsed){if(Model.layoutSettings[Model.layoutId]["transitionPoint"]!=undefined){Model.camera.state.position=MapUtils.getClone(Model.layoutSettings[Model.layoutId]["transitionPoint"]);}
else{log.error("no transition point found",this);}}
Model.camera.setFocusGeometry(Model.content.allGarmentsData[garmentId]["geometryName"],Model.content.allGarmentsData[garmentId]["transform"],garmentId);}
this.executeCamera(Model.camera);}
}
CameraController.prototype.setCameraCenter=function(x,y){
var max=3.1416 / 4.0;
var width=Model.imageWidth;var height=Model.imageHeight;
var thetaY=0.88;var thetaX=thetaY * width / height;
var ry=((x/width)-0.5)* thetaX;var rx=((y/height)-0.5)* thetaY;
var newYAngle=Model.camera.state["rotation"][1]+ry;var newXAngle=Model.camera.state["rotation"][0]+rx;
var newState={"fov":Model.camera.state["fov"],"position":[Model.camera.state["position"][0],Model.camera.state["position"][1],Model.camera.state["position"][2]],"rotation":[newXAngle,newYAngle,0]};
var newCameraTarget=new Array();
newCameraTarget=MapUtils.putAll(newCameraTarget,Model.camera.focusGeometry);
this.executeSetCamera(newState,newCameraTarget);}
CameraController.prototype.getZoomUrl=function(width,height){width=width==undefined?800 : width;height=height==undefined?600 : height;
return Model.getUpdatedMPSImageUrl(Model.VMContext)+"&w="+width+"&h="+height;}
function ModelContentController(id,parentClass){
this.id=id;this.parentClass=parentClass;
return this;}
ModelContentController.prototype.CATEGORY_ALL="All";
ModelContentController.prototype.id="Model.content";ModelContentController.prototype.onMyModelArray=new Array();ModelContentController.prototype.allGarmentsArray=new Array();ModelContentController.prototype.allItemsArray=new Array();ModelContentController.prototype.allGarmentsData=new Array();ModelContentController.prototype.wornGarmentMap=new Array();ModelContentController.prototype.selectedItemId="";ModelContentController.prototype.parentClass=undefined;ModelContentController.prototype.totalPrice=0;ModelContentController.prototype.garmentCount=0;ModelContentController.prototype.isInitialized=false;ModelContentController.prototype.selectedCategoryName="";ModelContentController.prototype.lastTriedOnGarmentId=undefined;ModelContentController.prototype.isRemoveIncompatibleItems=false;ModelContentController.prototype.onMyModelInfo=undefined;ModelContentController.prototype.displayedItemCategoryMap=new Array();ModelContentController.prototype.displayedItemMap=undefined;
ModelContentController.prototype.init=function(){
resource.applyProperties(this.id+"Properties",this);
this.selectedCategoryName=this.CATEGORY_ALL;
Workspace.events.throwEvent(Workspace.events.EVENT_CONTROLLER_INITIALIZED,this);this.isInitialized=true;
Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);}
ModelContentController.prototype.updateItems=function(){Items.loadItemInfo(this.onMyModelArray["allItemsIds"],this.id+".updateItemsGrouping();");}
ModelContentController.prototype.updateItemsGrouping=function(){Items.loadItemGroupingInfos(this.allItemsArray,this.id+".setData();");}
ModelContentController.prototype.itemIsInstanceOfCategory=function(itemId,subCategoryId){var foundCategory=false;
if(this.displayedItemMap[itemId]!=undefined){if(this.displayedItemMap[itemId]["CATEGORIES"]!=undefined){for(var categoryIndex in this.displayedItemMap[itemId]["CATEGORIES"]){foundCategory=(subCategoryId==this.displayedItemMap[itemId]["CATEGORIES"][categoryIndex]["CATEGORY_ID"]);if(foundCategory)break;}}}
return foundCategory;}
ModelContentController.prototype.getOnMyModelInfo=function(){
var onMyModelInfoMap=new Array();var itemList=new Array();var isSelectedItemInList=false;var commonColors=new Array();
this.selectedCategoryName=(this.displayedItemCategoryMap[this.selectedCategoryName]==undefined?this.CATEGORY_ALL : this.selectedCategoryName)
for(var itemId in this.displayedItemMap){
if(this.selectedCategoryName==this.CATEGORY_ALL||(this.displayedItemMap[itemId]["CATEGORIES"][0]["CATEGORY_ID"]!=undefined&&CatalogCategory.categoryMap!=undefined&&this.selectedCategoryName==CatalogCategory.categoryMap[this.displayedItemMap[itemId]["CATEGORIES"][0]["CATEGORY_ID"]]["CATEGORY_DESC"])){
itemList[itemList.length]=this.displayedItemMap[itemId];
if(itemId==this.selectedItemId){isSelectedItemInList=true;}}}
if(!isSelectedItemInList&&itemList.length>0){this.selectedItemId=itemList[0]["ID_ITEM"];}
for(var colorIndex in this.onMyModelArray["commonColors"]){
if(Items.getItemFromItemId(this.selectedItemId)["ITEM_GROUPING"]!=undefined){for(var itemGroupingIndex in Items.getItemFromItemId(this.selectedItemId)["ITEM_GROUPING"]){
var itemGroupingId=Items.getItemFromItemId(this.selectedItemId)["ITEM_GROUPING"][itemGroupingIndex];
if(Items.getItemFromItemId(itemGroupingId)["TYPE_ITEMS"]!="I"){for(var garementIndex in Items.getItemFromItemId(itemGroupingId)["GARMENTS"]){
var colorId=Items.getItemFromItemId(itemGroupingId)["GARMENTS"][garementIndex]["ID_COLOUR"];
if(this.onMyModelArray["commonColors"][colorIndex]["COLOUR_ID"]==colorId){
commonColors[commonColors.length]=MapUtils.getClone(this.onMyModelArray["commonColors"][colorIndex]);}}}}}
}
var selectedItemInfoMap=new Array();selectedItemInfoMap=MapUtils.getClone(Items.getItemFromItemId(this.selectedItemId));selectedItemInfoMap["THUMBNAIL_URL"]=selectedItemInfoMap["THUMBNAIL_URL"];selectedItemInfoMap["INSTANCES"]=this.getItemInstanceCount(this.selectedItemId);selectedItemInfoMap["COMMONCOLORS_DISPLAYED"]=commonColors;
onMyModelInfoMap["ITEM_LIST"]=itemList;onMyModelInfoMap["TOTAL_PRICE"]=setNumberDecimals(this.totalPrice);onMyModelInfoMap["CATEGORY_LIST"]=this.displayedItemCategoryMap;onMyModelInfoMap["SELECTED_CATEGORY"]=this.selectedCategoryName;onMyModelInfoMap["SELECTED_ITEM"]=selectedItemInfoMap;
return onMyModelInfoMap;}
ModelContentController.prototype.getWornGarment=function(pItemId){
var item=Items.getItemFromItemId(pItemId);var foundGarment=undefined;var i,j;
if(item!=undefined){
i=0;while(i<item["GARMENTS"].length&&foundGarment==undefined){
var garment=item["GARMENTS"][i];var garmentId=garment["ID_GARMENT"];
j=0;while(j<this.allGarmentsArray.length&&foundGarment==undefined){if(parseInt(this.allGarmentsArray[j])==parseInt(garmentId)){foundGarment=garment;}
j++;}
i++;}}
return foundGarment}
ModelContentController.prototype.removeSelectedItem=function(){
if(this.selectedItemId!=""){
var instancesInfo=this.onMyModelArray["instancesPerGarment"];
if(instancesInfo[garmentId]!=undefined){
var garmentIdList="";var garmentId="";var itemInfo=Items.getItemFromItemId(this.selectedItemId);
for(var garmentIndex in itemInfo["GARMENTS"]){
garmentId=itemInfo["GARMENTS"][garmentIndex]["ID_GARMENT"];
for(var instanceIndex in instancesInfo[garmentId]){garmentIdList+=(garmentIdList!=""?"," : "")+garmentId+":"+instancesInfo[garmentId][instanceIndex];}}
if(garmentIdList!=""){Model.removeGarments(garmentIdList);}
}else{Model.removeItems(this.selectedItemId);}}}
ModelContentController.prototype.addAllGoTogethers=function(){
if(this.getOnMyModelInfo()["SELECTED_ITEM"]!=undefined){
if(this.getOnMyModelInfo()["SELECTED_ITEM"]["GOTOGETHERS"]!=undefined){var itemsToAdd=this.getOnMyModelInfo()["SELECTED_ITEM"]["GOTOGETHERS"][0]["ITEMS"];var garmentsToAdd=new Array();
for(var index in itemsToAdd){
if(Items.isCompatible(itemsToAdd[index])&&Items.isAvailable(itemsToAdd[index])){garmentsToAdd[garmentsToAdd.length]=Items.getFirstAvailableGarment(itemsToAdd[index]);}}
Model.tryOnItems(garmentsToAdd.join(","));}}}
ModelContentController.prototype.updateUndoRedoState=function(pUndoState,pRedoState){
var undoRedoElement=document.getElementById("undoButton");
if(undoRedoElement!=undefined){if(pUndoState=="true"){undoRedoElement.setAttribute("mode","undo");undoRedoElement.setAttribute("state","normal");}else if(pRedoState=="true"){undoRedoElement.setAttribute("mode","redo");undoRedoElement.setAttribute("state","normal");}else{undoRedoElement.setAttribute("mode","undo");undoRedoElement.setAttribute("state","disabled");}
undoRedoElement.src=undoRedoElement.getAttribute("src_"+undoRedoElement.getAttribute("mode")+"_"+undoRedoElement.getAttribute("state"));}}
ModelContentController.prototype.getGarmentIdFromFilename=function(imageUrl){
var filenameMap=this.onMyModelArray["filenamesPerGarment"];var tmpGarmentId=undefined;
for(var garmentId in filenameMap){for(var filenameIndex in filenameMap[garmentId]){if(filenameMap[garmentId][filenameIndex]==imageUrl&&this.wornGarmentMap[garmentId]!=undefined){return garmentId;break;}}}}
ModelContentController.prototype.getGarmentIdFromGeometry=function(geometryKey,geometryName){
var filenameMap=this.onMyModelArray["filenamesPerGarment"];
for(var garmentId in filenameMap){
for(var filenameIndex in filenameMap[garmentId]){
if(Model.compareKeys(filenameMap[garmentId][filenameIndex],geometryKey)&&this.wornGarmentMap[garmentId]!=undefined){
return garmentId;break;}}}}
ModelContentController.prototype.getItemInstanceCount=function(itemId){
return(this.onMyModelArray["itemInstanceMap"]!=undefined?this.onMyModelArray["itemInstanceMap"][itemId] : undefined);}
ModelContentController.prototype.setData=function(){
this.displayedItemMap=new Array();this.totalPrice=0;this.garmentCount=0;this.displayedItemCategoryMap=new Array();this.displayedItemCategoryMap[this.CATEGORY_ALL]=this.CATEGORY_ALL;this.wornGarmentMap=new Array();
this.onMyModelArray["itemInstanceMap"]=new Array();
var item=undefined;
var index=0;var categoryName="";var itemId="";var garmentId="";var itemInfoMap=undefined;
for(var i=0;i<this.onMyModelArray["allItemsIds"].length;i++){
itemId=this.onMyModelArray["allItemsIds"][i];item=Items.getItemFromItemId(itemId);
if(item!=undefined&&Items.isAvailable(itemId)&&!Items.isFallback(itemId)){
var wornGarment=MapUtils.getClone(this.getWornGarment(itemId));if(wornGarment!=undefined){
wornGarment["ITEM"]=Items.getItemFromItemId(itemId);garmentId=wornGarment["ID_GARMENT"];
if(this.onMyModelArray["instancesPerGarment"][garmentId]!=undefined){
for(var instanceIndex in this.onMyModelArray["instancesPerGarment"][garmentId]){this.wornGarmentMap[garmentId+":"+this.onMyModelArray["instancesPerGarment"][garmentId][instanceIndex]]=wornGarment;}
this.garmentCount+=this.onMyModelArray["instancesPerGarment"][garmentId].length;this.onMyModelArray["itemInstanceMap"][itemId]=this.onMyModelArray["instancesPerGarment"][garmentId].length;}else{
this.wornGarmentMap[garmentId]=wornGarment;this.garmentCount++;this.onMyModelArray["itemInstanceMap"][itemId]=1;}
this.totalPrice+=parseFloat(item["PRICE2"]!=undefined?item["PRICE2"] : 0);
if(item["CATEGORIES"]!=undefined&&item["CATEGORIES"][0]["CATEGORY_ID"]!=undefined&&CatalogCategory!=undefined&&CatalogCategory.categoryMap!=undefined&&CatalogCategory.categoryMap[item["CATEGORIES"][0]["CATEGORY_ID"]]!=undefined){categoryName=CatalogCategory.categoryMap[item["CATEGORIES"][0]["CATEGORY_ID"]]["CATEGORY_DESC"];}else{categoryName="Other";}
this.displayedItemCategoryMap[categoryName]=categoryName;
itemInfoMap=new Array();itemInfoMap=MapUtils.getClone(Items.getItemFromItemId(itemId));itemInfoMap["THUMBNAIL_URL"]=itemInfoMap["THUMBNAIL_URL"];itemInfoMap["CATEGORY_NAME"]=categoryName;
this.displayedItemMap[itemId]=itemInfoMap;
}}}
this.totalPrice=setNumberDecimals(this.totalPrice);
var lastTriedOnItem=Items.getItemFromGarmentId(this.lastTriedOnGarmentId);var lastTriedOnGarmentId=this.lastTriedOnGarmentId;var lastSelectedItem=Items.getItemFromItemId(this.selectedItemId);
if(this.onMyModelArray["allItemsIds"].length==0){this.selectedItemId="";}else if(lastTriedOnItem!=undefined){this.selectedItemId=lastTriedOnItem["ID_ITEM"];this.lastTriedOnGarmentId=undefined;
}else if(lastSelectedItem!=undefined){this.selectedItemId=this.selectedItemId;
}else if(this.onMyModelArray["allItemsIds"].length>0){this.selectedItemId=this.onMyModelArray["allItemsIds"][0];
}else if(lastSelectedItem==undefined){this.selectedItemId="";}
if(Model.rendererType=="RT3D"&&lastTriedOnGarmentId!=undefined&&!Model.isInstanceSelectionMode){
if(lastTriedOnGarmentId.indexOf(":")>=0){Model.setBestView(lastTriedOnGarmentId);}
else{
if(this.onMyModelArray["instancesPerGarment"][lastTriedOnGarmentId]!=undefined){var instanceId=this.onMyModelArray["instancesPerGarment"][lastTriedOnGarmentId][0];Model.setBestView(lastTriedOnGarmentId+":"+instanceId);}
else{
Model.setBestView(lastTriedOnGarmentId+":1");}}}
this.onMyModelInfo=this.getOnMyModelInfo();
Items.loadGreatGoTogetherItems(this.selectedItemId);
if(Model.isRestoreWornGarmentsFromCookie){State.set("wornGarments",encodeURIComponent(this.allGarmentsArray.join(",")));}
if(this.onMyModelArray["itemInstanceMap"]==undefined||this.onMyModelArray["itemInstanceMap"][this.selectedItemId]==undefined){this.selectedItemId="";}
Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_CONTENT_CHANGED,this);}
ModelContentController.prototype.createGeometryNames=function(){
for(var garmentId in this.allGarmentsData){
this.allGarmentsData[garmentId]["geometryName"]=constructGeometryName(this.allGarmentsData[garmentId]["itemId"],this.allGarmentsData[garmentId]["colorId"],this.allGarmentsData[garmentId]["state"]);}}
/**
* Logic to handle the trigger of events when incompatible/alternate items were tried on
*/
ModelContentController.prototype.handleIncompatibleItem=function(attributes){
if(attributes.response["errorCode"]=="incompatibleItem"){
if(attributes.action=="tryOn"){Workspace.events.throwEvent(Workspace.events.EVENT_INCOMPATIBLE_ITEM_TRYON,attributes);
}else{Workspace.events.throwEvent(Workspace.events.EVENT_INCOMPATIBLE_ITEM_REMOVED,attributes);}
}else if(attributes.response["statusCode"]=="alternateItemUseCase"){
if(attributes.action=="tryOn"){Workspace.events.throwEvent(Workspace.events.EVENT_ALTERNATE_ITEM_TRYON,attributes);
}else{Workspace.events.throwEvent(Workspace.events.EVENT_INCOMPATIBLE_ITEM_ALTERNATE,attributes);}
}}
ModelContentController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED&&attributes!=undefined&&attributes.response!=undefined){
if(attributes.response["allGarmentIds"]!=undefined&&attributes.parametersMap["isDefaultWear"]!="true"&&attributes.parametersMap["imageElementId"]==undefined){
this.onMyModelArray=MapUtils.getClone(attributes.response);
this.lastTriedOnGarmentId=attributes.parametersMap["garmentsID"];this.allGarmentsData=this.onMyModelArray["onMyModelDataPerGarment"];this.allItemsArray=this.onMyModelArray["allItemsIds"];this.allGarmentsArray=this.onMyModelArray["allGarmentIds"];
if(Model.rendererType=="RT3D"){this.createGeometryNames();}
setTimeout(this.id+".updateItems()",10);
if(attributes.response["undoStatus"]!=undefined&&attributes.response["redoStatus"]!=undefined){this.updateUndoRedoState(attributes.response["undoStatus"],attributes.response["redoStatus"]);}
}
if(attributes.callingController==Model){this.handleIncompatibleItem(attributes);}}}
function OnMyModelController(id){
this.id=id;return this;}
OnMyModelController.prototype.CATEGORY_ALL="All";
OnMyModelController.prototype.id="OnMyModelController";OnMyModelController.prototype.elementId="OnMyModelWindow";OnMyModelController.prototype.handlerUrl="";OnMyModelController.prototype.swatchUrl="";OnMyModelController.prototype.thumbnailPrefix="";OnMyModelController.prototype.thumbnailSuffix="";OnMyModelController.prototype.totalPrice=0;OnMyModelController.prototype.isGenerated=false;OnMyModelController.prototype.printPopupHandle=undefined;OnMyModelController.prototype.isInitialized=false;OnMyModelController.prototype.buyOutfitUrlTemplate="";OnMyModelController.prototype.lastSelectedItemId="";
OnMyModelController.prototype.init=function(){
resource.applyProperties(this.id+"Properties",this);
Workspace.events.throwEvent(Workspace.events.EVENT_CONTROLLER_INITIALIZED,this);this.isInitialized=true;
Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);Workspace.events.addListener(Workspace.events.EVENT_MODEL_CONTENT_CHANGED,this);}
OnMyModelController.prototype.show=function(){
if(!this.isGenerated){this.isGenerated=true;Model.content.selectedCategoryName=this.CATEGORY_ALL;this.update();}}
OnMyModelController.prototype.update=function(){
if(this.isGenerated){ParserUtils.applyTemplate(this.id+"Template",this.id+"Container",Model.content.getOnMyModelInfo());}
var selectedItem=Items.getItemFromItemId(Model.content.selectedItemId);
if(selectedItem!=undefined&&MapUtils.getMapValue("GOTOGETHERS/0/ITEMS/0",selectedItem)!=undefined){Items.loadItemInfo(Items.getItemFromItemId(Model.content.selectedItemId)["GOTOGETHERS"][0]["ITEMS"],this.id+".displayGreatGoTogethers()");}else{this.displayGreatGoTogethers();}
if(Model.isRestoreWornGarmentsFromCookie){State.set("wornGarments",encodeURIComponent(Model.content.allGarmentsArray.join(",")));}
if(this.lastSelectedItemId!=Model.content.selectedItemId){Workspace.events.throwEvent(Workspace.events.EVENT_ONMYMODEL_ITEM_SELECTED,this);}
this.lastSelectedItemId=Model.content.selectedItemId;}
OnMyModelController.prototype.displayGreatGoTogethers=function(){
if(this.isGenerated){ParserUtils.applyTemplate("GreatGoTogethersTemplate","GreatGoTogethersContainer");}}
OnMyModelController.prototype.setCategory=function(categoryName){
Model.content.selectedCategoryName=categoryName;this.update();}
OnMyModelController.prototype.showItemInfo=function(itemId,garmentId){
var itemInfo=undefined;
if(itemId!=undefined){itemInfo=Items.getItemFromItemId(itemId);}else if(garmentId!=undefined){itemInfo=Items.getItemFromGarmentId(garmentId);}
if(itemInfo!=undefined&&Model.content.selectedItemId!=itemInfo["ID_ITEM"]){Model.content.selectedItemId=itemInfo["ID_ITEM"];this.update();}}
OnMyModelController.prototype.callBuyOutfitPage=function(){
if(Model.content.onMyModelArray["allItemsIds"].length>0){
var itemList=new Array();var colorList=new Array();
for(var i=0;i<Model.content.onMyModelArray["allItemsIds"].length;i++){var garment=Model.content.getWornGarment(Model.content.onMyModelArray["allItemsIds"][i]);
if(garment!=undefined){itemList[itemList.length]=Model.content.onMyModelArray["allItemsIds"][i];colorList[colorList.length]=garment["ID_GARMENT"];}}
var params=new Array();params[params.length]=["params","i:"+itemList.join(",")+";c:"+colorList.join(",")];params[params.length]=["eventKey","BuyOutf"];
this.sendRequest("logEvent",params,Workspace.serverContext+"/action/logEvent");
Workspace.callUrlInParent(ParserUtils.parseHtml(this.buyOutfitUrlTemplate,this));
Workspace.events.throwEvent(Workspace.events.EVENT_BUYOUTFIT_PAGE_CALL,this);}}
OnMyModelController.prototype.callProductPage=function(itemId){
var item=Items.getItemFromItemId(itemId);
if(item!=undefined){
var params=new Array();params[params.length]=["params","il:"+itemId];params[params.length]=["eventKey","Buy"];
this.sendRequest("logEvent",params,Workspace.serverContext+"/action/logEvent");
Workspace.events.throwEvent(Workspace.events.EVENT_PRODUCT_PAGE_CALL,item);
Workspace.callUrlInParent(decodeURIComponent(item["PRODUCT_PAGE_URL"]));}}
OnMyModelController.prototype.addAllGoTogethers=function(){
if(this.getOnMyModelInfo()["SELECTED_ITEM"]!=undefined){
if(this.getOnMyModelInfo()["SELECTED_ITEM"]["GOTOGETHERS"]!=undefined){var itemsToAdd=this.getOnMyModelInfo()["SELECTED_ITEM"]["GOTOGETHERS"][0]["ITEMS"];var garmentsToAdd=new Array();
for(var index in itemsToAdd){
if(Items.isCompatible(itemsToAdd[index])&&Items.isAvailable(itemsToAdd[index])){garmentsToAdd[garmentsToAdd.length]=Items.getFirstAvailableGarment(itemsToAdd[index]);}}
Model.tryOnItems(garmentsToAdd.join(","));}}}
OnMyModelController.prototype.print=function(width,height){
ParserUtils.preloadTemplate(this.id+"PrintTemplate",this.id+".openPrintPopup("+width+","+height+")");}
OnMyModelController.prototype.openPrintPopup=function(width,height){
var winWidth=(width!=undefined?width : 580);var winHeight=(height!=undefined?height : 500);
this.printPopupHandle=window.open("","printwin","width="+winWidth+",height="+winHeight+",scrollbars=1");this.printPopupHandle.focus();this.printPopupHandle.document.open("text/html","replace");this.printPopupHandle.document.write(ParserUtils.parseTemplate(this.id+"PrintTemplate",this));this.printPopupHandle.document.close();}
OnMyModelController.prototype.sendRequest=function(pActionType,pParams,handlerUrl){
handlerUrl=(handlerUrl!=undefined?handlerUrl : this.handlerUrl);
var requestParams=new Array();
requestParams=requestParams.concat(pParams);
det.sendRequest({serverUrl:handlerUrl,action:pActionType,parameters:requestParams,callingController:this});}
OnMyModelController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED&&attributes!=undefined&&attributes.response!=undefined){}else if(eventKey==Workspace.events.EVENT_MODEL_CONTENT_CHANGED){this.update();}}
function ModelMapController(id){
this.id=id;}
ModelMapController.prototype.X1=0;ModelMapController.prototype.Y1=1;ModelMapController.prototype.X2=2;ModelMapController.prototype.Y2=3;
ModelMapController.prototype.id="ModelMapController";ModelMapController.prototype.outlineElementId="itemOutliner";ModelMapController.prototype._jsGraphics=undefined;ModelMapController.prototype.mapArray=new Array();ModelMapController.prototype.allPolygons=new Array();ModelMapController.prototype.highlightedGarmentId="";ModelMapController.prototype.highlightedInstanceId="";ModelMapController.prototype._isEnabled=true;ModelMapController.prototype.thread=undefined;ModelMapController.prototype.mapBoundingBoxArray=new Array();ModelMapController.prototype.handlerUrl=undefined;ModelMapController.prototype.multiplePolygonColors=undefined;ModelMapController.prototype.mapResponse=undefined;ModelMapController.prototype.requestTimeout=10000;ModelMapController.prototype.mouseX=0;ModelMapController.prototype.mouseY=0;ModelMapController.prototype.isDrawPolygons=true;
ModelMapController.prototype.init=function(){
resource.applyProperties(this.id+"Properties",this);
Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);Workspace.events.addListener(Workspace.events.EVENT_MODEL_IMAGE_CHANGED,this);Workspace.events.addListener(Workspace.events.EVENT_MODEL_ONMOUSEOVER,this);
this.handlerUrl=Workspace.serverContext+"/action/modeldisplay";
this.initGraphics();
if(Workspace.query.param1==undefined){this.loadMap();}
Workspace.events.throwEvent(Workspace.events.EVENT_CONTROLLER_INITIALIZED,this);}
ModelMapController.prototype.initGraphics=function(){
if(isDefined("jsGraphics")){this._jsGraphics=new jsGraphics(this.outlineElementId);}}
ModelMapController.prototype.zoomOnGarment=function(garmentId){
var boundingBox=this.mapBoundingBoxArray[garmentId];
if(boundingBox!=undefined&&typeof(Model)!="undefined"){
Model.zoom(
boundingBox[this.X1]+((boundingBox[this.X2]-boundingBox[this.X1])/2),boundingBox[this.Y1]+((boundingBox[this.Y2]-boundingBox[this.Y1])/2));}}
ModelMapController.prototype.getGarmentIdFromCoordinate=function(pX,pY,isUseCompletePolygon){
var returnValue=undefined;var polygonInfo=undefined;var garmentIdList=new Array();isUseCompletePolygon=isUseCompletePolygon!=undefined?isUseCompletePolygon : false;
for(var garmentId in this.mapBoundingBoxArray){
if(this.isPointInBoundingBox(pX,pY,this.mapBoundingBoxArray[garmentId])){
if(isUseCompletePolygon){var polyInfo=this.getPolygonInfoFromCoordinate(pX,pY);if(polyInfo!=undefined&&polyInfo["garmentId"]!=undefined){garmentIdList.push(garmentId);break;}}else{garmentIdList.push(garmentId);}}}
if(garmentIdList.length>1){
for(var i=0;i<garmentIdList.length;i++){
for(key in this.mapArray[garmentIdList[i]]["polygons"]){if(returnValue==undefined&&this.isPointInPolygonGroup(pX,pY,this.mapArray[garmentIdList[i]]["polygons"][key])){returnValue=garmentIdList[i];}}}
}else if(garmentIdList.length==1){returnValue=garmentIdList[0];}
return returnValue;}
ModelMapController.prototype.getPolygonInfoFromCoordinate=function(pX,pY,isSkipNonLinkedPolygons,garmentIdLookup){
var polygonsBoundingBox=undefined;var matchingBoundingBoxPolygonsKey=new Array();var foundKey=undefined;
for(var key in this.allPolygons){
if(!isSkipNonLinkedPolygons||(isSkipNonLinkedPolygons&&this.allPolygons[key]["garmentId"]!=undefined)){
polygonsBoundingBox=this.getBoundingBox(this.allPolygons[key]["include"].join(" "));
if(polygonsBoundingBox[this.X2]-polygonsBoundingBox[this.X1]<20||polygonsBoundingBox[this.Y2]-polygonsBoundingBox[this.Y1]<20){
polygonsBoundingBox[this.X1]-=10;polygonsBoundingBox[this.Y1]-=10;polygonsBoundingBox[this.X2]+=10;polygonsBoundingBox[this.Y2]+=10;}
if(this.isPointInBoundingBox(pX,pY,polygonsBoundingBox)){matchingBoundingBoxPolygonsKey.push(key);}}}
if(matchingBoundingBoxPolygonsKey.length==1){foundKey=matchingBoundingBoxPolygonsKey[0];
}else if(matchingBoundingBoxPolygonsKey.length>1){for(var index in matchingBoundingBoxPolygonsKey){if(this.isPointInPolygonGroup(pX,pY,this.allPolygons[matchingBoundingBoxPolygonsKey[index]])){foundKey=matchingBoundingBoxPolygonsKey[index];break;}}}
if(foundKey!=undefined){return this.allPolygons[foundKey];}else{return undefined;}}
ModelMapController.prototype.isPointInPolygonGroup=function(pX,pY,polygonInfo){
var isInPolygonGroup=false;
for(var i=0;i<polygonInfo["include"].length;i++){if(this.isPointInPolygon(pX,pY,polygonInfo["include"][i])){
isInPolygonGroup=true;
for(var j=0;j<polygonInfo["exclude"].length;j++){if(this.isPointInPolygon(pX,pY,polygonInfo["exclude"][j])){isInPolygonGroup=false;break;}}
if(isInPolygonGroup){break;}}
if(isInPolygonGroup){break;}}
return isInPolygonGroup}
ModelMapController.prototype.displayPolygon=function(garmentId,isDisplayPopup,templateId){
isDisplayPopup=isDisplayPopup==undefined?true : isDisplayPopup;templateId=templateId==undefined?"mouseOver" : templateId;
var coordArray=undefined;var xArray=undefined;var yArray=undefined;
if(this._jsGraphics==undefined){this.initGraphics();}
if(this._isEnabled&&this.mapArray!=undefined&&this.mapArray[garmentId]!=undefined&&this.highlightedGarmentId+(this.highlightedInstanceId!=""?":"+this.highlightedInstanceId : "")!=garmentId){
this.resetItemHighlight();
if(garmentId.indexOf(":")>-1){this.highlightedGarmentId=garmentId.split(":")[0];this.highlightedInstanceId=garmentId.split(":")[1];}else{this.highlightedGarmentId=garmentId;this.highlightedInstanceId="";}
if(this.isDrawPolygons){
this._jsGraphics.setStroke(1);this._jsGraphics.setColor("#ffffff");
for(key in this.mapArray[garmentId]["polygons"]){this.drawPolygon(this.mapArray[garmentId]["polygons"][key]["include"]);this._jsGraphics.paint();}}
if(this.thread!=undefined){clearTimeout(this.thread);this.thread=undefined;}
if(isDisplayPopup){}
}}
ModelMapController.prototype.updateMousePointer=function(mouseLeft,mouseTop){
mouseLeft=mouseLeft-getAbsLeft(getE('modelContainer'));mouseTop=mouseTop-getAbsTop(getE('modelContainer'));
var garmentId=this.getGarmentIdFromCoordinate(mouseLeft,mouseTop,true);
if(garmentId!=undefined){
this.highlightedGarmentId=garmentId;
getE('modelContainer').style.cursor="pointer";}else{
getE('modelContainer').style.cursor="default";}}
ModelMapController.prototype.drawPolygon=function(coordinatesList,isPaintAfter){
isPaintAfter=(isPaintAfter!=undefined?isPaintAfter : false);
var nodesCount=0;
for(var i=0;i<coordinatesList.length;i++){
coordArray=coordinatesList[i].split(" ");xArray=new Array();yArray=new Array();
for(var j=0;j<coordArray.length-1;j++){xArray.push(parseInt(coordArray[j].split(",")[this.X1]));yArray.push(parseInt(coordArray[j].split(",")[this.Y1]));}
nodesCount+=coordArray.length;
this._jsGraphics.drawPolygon(xArray,yArray);}
log.debug("drawing polygon with "+nodesCount+" points",this);
if(isPaintAfter){this._jsGraphics.paint();}}
ModelMapController.prototype.showAllPolygons=function(){
var coordArray=undefined;var xArray=undefined;var yArray=undefined;
if(this._jsGraphics==undefined){this.initGraphics();}
if(this.mapArray!=undefined){
this.resetItemHighlight();
this._jsGraphics.setStroke(2);
var count=0;
for(var key in this.allPolygons){
this._jsGraphics.setColor(this.multiplePolygonColors[count]);
this.drawPolygon(this.allPolygons[key]["include"].concat(this.allPolygons[key]["exclude"]));}
this._jsGraphics.paint();}}
ModelMapController.prototype.resetItemHighlight=function(){
if(this._jsGraphics==undefined){this.initGraphics();}
this._jsGraphics.clear();
this.highlightedGarmentId="";this.highlightedInstanceId="";
if(this.thread!=undefined){clearTimeout(this.thread);this.thread=undefined;}}
ModelMapController.prototype.setMapCompositor=function(pXMLArray){
this.mapArray=new Array();this.allPolygons=new Array();this.mapBoundingBoxArray=new Array();
var includedPolygons=undefined;var excludedPolygons=undefined;var boundingBox=undefined;
if(pXMLArray!=undefined&&pXMLArray["image-maps"]!=undefined&&(pXMLArray["image-maps"]["map"]!=undefined||pXMLArray["image-maps"]["map2"]!=undefined)){
var imageUrl="";var garmentId="";
var xmlArray=(pXMLArray["image-maps"]["map2"]!=undefined?pXMLArray["image-maps"]["map2"] : pXMLArray["image-maps"]["map"]);
for(var i=0;i<xmlArray.length;i++){
if(xmlArray[i]!=undefined){
imageUrl=(xmlArray[i]["image"]!=undefined?xmlArray[i]["image"][0] : xmlArray[i]["img"][0]);
garmentId=Model.content.getGarmentIdFromFilename(imageUrl);
includedPolygons=(xmlArray[i]["polygon_include"]!=undefined?xmlArray[i]["polygon_include"] : xmlArray[i]["coordinates"]);excludedPolygons=(xmlArray[i]["polygon_exclude"]!=undefined?xmlArray[i]["polygon_exclude"] : new Array());
if(includedPolygons!=undefined){
if(garmentId!=undefined){
if(this.mapArray[garmentId]==undefined){this.mapArray[garmentId]=new Array();this.mapArray[garmentId]["polygons"]=new Array();}
this.mapArray[garmentId]["polygons"][imageUrl]={"key":imageUrl,"garmentId":garmentId,"include":includedPolygons,"exclude":excludedPolygons};
if(this.mapBoundingBoxArray[garmentId]==undefined){this.mapBoundingBoxArray[garmentId]=this.getBoundingBox(includedPolygons.join(" "));}
else{newBoundingBox=this.getBoundingBox(includedPolygons.join(" "));
if(newBoundingBox[this.X1]<this.mapBoundingBoxArray[garmentId][this.X1]){this.mapBoundingBoxArray[garmentId][this.X1]=newBoundingBox[this.X1];}
if(newBoundingBox[this.X2]>this.mapBoundingBoxArray[garmentId][this.X2]){this.mapBoundingBoxArray[garmentId][this.X2]=newBoundingBox[this.X2];}
if(newBoundingBox[this.Y1]<this.mapBoundingBoxArray[garmentId][this.Y1]){this.mapBoundingBoxArray[garmentId][this.Y1]=newBoundingBox[this.Y1];}
if(newBoundingBox[this.Y2]>this.mapBoundingBoxArray[garmentId][this.Y2]){this.mapBoundingBoxArray[garmentId][this.Y2]=newBoundingBox[this.Y2];}}
if(this.mapBoundingBoxArray[garmentId][this.X2]-this.mapBoundingBoxArray[garmentId][this.X1]<10||this.mapBoundingBoxArray[garmentId][this.Y2]-this.mapBoundingBoxArray[garmentId][this.Y1]<10){
this.mapBoundingBoxArray[garmentId][this.X1]-=10;this.mapBoundingBoxArray[garmentId][this.Y1]-=10;this.mapBoundingBoxArray[garmentId][this.X2]+=10;this.mapBoundingBoxArray[garmentId][this.Y2]+=10;}}
if(imageUrl!=undefined){
this.allPolygons[imageUrl]=new Array();this.allPolygons[imageUrl]["key"]=imageUrl;this.allPolygons[imageUrl]["garmentId"]=garmentId;this.allPolygons[imageUrl]["include"]=includedPolygons;this.allPolygons[imageUrl]["exclude"]=excludedPolygons;}}}}
this.enable();Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_MAP_LOADED,this);
}else{log.error("setMap: XMLArray is not defined.",this);}}
ModelMapController.prototype.setMapMPS=function(pJSONMap){
this.mapArray=new Array();this.allPolygons=new Array();this.mapBoundingBoxArray=new Array();
var includedPolygons=undefined;var excludedPolygons=undefined;var boundingBox=undefined;
if(pJSONMap!=undefined&&pJSONMap["maps"]!=undefined){
var geometryName="";var geometryTransform=new Array();var garmentId="";var geometryKey="";
var JSONArray=pJSONMap["maps"]["0"]["geometry"];
for(var i=0;i<JSONArray.length;i++){
if(JSONArray[i]!=undefined){
geometryName=JSONArray[i]["geometryName"][0];geometryTransform=JSONArray[i]["transform"][0].split(",");
geometryKey=constructGeometryKey(geometryName,geometryTransform);
garmentId=Model.content.getGarmentIdFromGeometry(geometryKey,geometryName);
includedPolygons=(JSONArray[i]["polygon_include"]==undefined?new Array(): JSONArray[i]["polygon_include"]);excludedPolygons=(JSONArray[i]["polygon_exclude"]==undefined?new Array(): JSONArray[i]["polygon_exclude"]);
if(includedPolygons!=undefined){
if(garmentId!=undefined){
if(this.mapArray[garmentId]==undefined){this.mapArray[garmentId]=new Array();this.mapArray[garmentId]["polygons"]=new Array();}
this.mapArray[garmentId]["polygons"][geometryKey]={"key":geometryKey,"garmentId":garmentId,"include":includedPolygons,"exclude":excludedPolygons};
if(this.mapBoundingBoxArray[garmentId]==undefined){this.mapBoundingBoxArray[garmentId]=this.getBoundingBox(includedPolygons.join(" "));}
else{newBoundingBox=this.getBoundingBox(includedPolygons.join(" "));
if(newBoundingBox[this.X1]<this.mapBoundingBoxArray[garmentId][this.X1]){this.mapBoundingBoxArray[garmentId][this.X1]=newBoundingBox[this.X1];}
if(newBoundingBox[this.X2]>this.mapBoundingBoxArray[garmentId][this.X2]){this.mapBoundingBoxArray[garmentId][this.X2]=newBoundingBox[this.X2];}
if(newBoundingBox[this.Y1]<this.mapBoundingBoxArray[garmentId][this.Y1]){this.mapBoundingBoxArray[garmentId][this.Y1]=newBoundingBox[this.Y1];}
if(newBoundingBox[this.Y2]>this.mapBoundingBoxArray[garmentId][this.Y2]){this.mapBoundingBoxArray[garmentId][this.Y2]=newBoundingBox[this.Y2];}}
if(this.mapBoundingBoxArray[garmentId][this.X2]-this.mapBoundingBoxArray[garmentId][this.X1]<10||this.mapBoundingBoxArray[garmentId][this.Y2]-this.mapBoundingBoxArray[garmentId][this.Y1]<10){
this.mapBoundingBoxArray[garmentId][this.X1]-=10;this.mapBoundingBoxArray[garmentId][this.Y1]-=10;this.mapBoundingBoxArray[garmentId][this.X2]+=10;this.mapBoundingBoxArray[garmentId][this.Y2]+=10;}}
if(geometryName!=undefined){
this.allPolygons[geometryKey]=new Array();this.allPolygons[geometryKey]["key"]=geometryKey;this.allPolygons[geometryKey]["garmentId"]=garmentId;this.allPolygons[geometryKey]["include"]=includedPolygons;this.allPolygons[geometryKey]["exclude"]=excludedPolygons;}}}}
this.enable();Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_MAP_LOADED,this);
}else{log.error("setMap: JSON map is not defined.",this);}
}
ModelMapController.prototype.loadMap=function(rendererUrl){
this.disable();
var finalUrl="";var responseFormat="";
if(Model.rendererType=="CS"){
rendererUrl=(rendererUrl!=undefined?rendererUrl : Model.modelImageUrl);finalUrl=Model.getUpdatedCompositorImageUrl(rendererUrl);finalUrl=rendererUrl.replace(/im=y/,"im=r");responseFormat=det.RESPONSE_FORMAT_XML;}else{
if(rendererUrl!=undefined){finalUrl=rendererUrl;}else{finalUrl=Model.getUpdatedMPSImageUrl(Model.VMContext);}
responseFormat=det.RESPONSE_FORMAT_XML;
finalUrl=finalUrl.replace(/m=r/,"m=d"+Model.camera.getMPSDataString());}
this.sendRequest(finalUrl,"compositor","",responseFormat);}
ModelMapController.prototype.getBoundingBox=function(pCoordinates){
var leftMost=undefined;var topMost=undefined;var rightMost=undefined;var bottomMost=undefined;var coordinateSetArray=pCoordinates.split(" ");var leftPos=0;var topPos=0;
for(var i=0;i<coordinateSetArray.length;i++){
leftPos=coordinateSetArray[i].split(",")[0];topPos=coordinateSetArray[i].split(",")[1];
if(leftMost==undefined||parseInt(leftPos)<parseInt(leftMost)){leftMost=leftPos;}
if(topMost==undefined||parseInt(topPos)<parseInt(topMost)){topMost=topPos;}
if(rightMost==undefined||parseInt(leftPos)>parseInt(rightMost)){rightMost=leftPos;}
if(bottomMost==undefined||parseInt(topPos)>parseInt(bottomMost)){bottomMost=topPos;}}
return new Array(parseInt(leftMost),parseInt(topMost),parseInt(rightMost),parseInt(bottomMost));}
ModelMapController.prototype.isPointInPolygon=function(pX,pY,pPolygonCoordinates){
var i=0;var j=0;var oddNODES=false;
var coordArray=pPolygonCoordinates.split(" ");var polyX=new Array();var polyY=new Array();
for(var i=0;i<coordArray.length-1;i++){polyX.push(parseInt(coordArray[i].split(",")[this.X1]));polyY.push(parseInt(coordArray[i].split(",")[this.Y1]));}
for(var i=0;i<polyX.length;i++){j++;
if(j==polyX.length){j=0;}
if(polyY[i]<pY&&polyY[j]>=pY||polyY[j]<pY&&polyY[i]>=pY){if(polyX[i]+(pY-polyY[i])/(polyY[j]-polyY[i])*(polyX[j]-polyX[i])<pX){oddNODES=!oddNODES;}}}
return oddNODES;}
ModelMapController.prototype.isPointInBoundingBox=function(pX,pY,boundingBox){
if(pX>=boundingBox[this.X1]&&pY>=boundingBox[this.Y1]&&pX<=boundingBox[this.X2]&&pY<=boundingBox[this.Y2]){return true;}else{return false;}}
ModelMapController.prototype.displaySelectedPolygon=function(){
var garmentId=this.getGarmentIdFromCoordinate(this.mouseX,this.mouseY);
if(garmentId!=undefined){if(this.highlightedGarmentId+(this.highlightedInstanceId!=""?":"+this.highlightedInstanceId : "")!=garmentId){this.resetItemHighlight();this.displayPolygon(garmentId,false);}}else{this.resetItemHighlight();Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_ITEM_MOUSEOUT);}}
ModelMapController.prototype.sendRequest=function(pServerURL,pAction,pParams,responseFormat){
det.sendRequest({serverUrl:pServerURL,action:pAction,parameters:pParams,callingController:this,timeout:this.requestTimeout,method:"GET",responseFormat:(responseFormat!=undefined?responseFormat : det.RESPONSE_FORMAT_XML)});}
ModelMapController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED&&attributes.callingController==this){if(attributes!=undefined&&attributes.response!=undefined){
if(attributes.response["image-maps"]!=undefined){this.setMapCompositor(attributes.response);}
if(attributes.response["result"]!=undefined){if(attributes.response["result"]["maps"]!=undefined){
this.setMapMPS(attributes.response["result"]);
}}
}
}else if(eventKey==Workspace.events.EVENT_MODEL_ONMOUSEOVER&&!Model.isInstanceSelectionMode&&!Model.isZoomedIn&&!Model.isEnlarged&&!Workspace.message.isCursorOver(this.id+"Callout",attributes["mouseX"],attributes["mouseY"])&&Model.afterBestViewAction==undefined){
this.mouseX=attributes["mouseX"];this.mouseY=attributes["mouseY"];
this.displaySelectedPolygon();
Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_ITEM_MOUSEOVER,ModelMap.highlightedGarmentId+(ModelMap.highlightedInstanceId!=""?":"+ModelMap.highlightedInstanceId : ""));
}else if(eventKey==Workspace.events.EVENT_MODEL_IMAGE_CHANGED){if(!Model.isInstanceSelectionMode){this.resetItemHighlight();this.loadMap();}}}
ModelMapController.prototype.enable=function(){
log.info("ModelMap is enabled",this);this._isEnabled=true;}
ModelMapController.prototype.disable=function(){
log.info("ModelMap is disabled",this);this._isEnabled=false;this.resetItemHighlight();}
function FitQuestionnaireController(id){jsClass.extend(this,[QuestionnaireController]);
this.id=id;this.domain=Workspace.population;}
FitQuestionnaireController.prototype.questionSet="M";FitQuestionnaireController.prototype.isAutomaticModelUpdate=true;
FitQuestionnaireController.prototype.init=function(){
this.handlerUrl=Workspace.serverContext+"/action/";this.super_QuestionnaireController_init();
this.defaultAnswersMap=this.defaultAnswersMap[Workspace.population];this.answerMap=new Array();this.setAnswersMap(this.defaultAnswersMap);
if(!Workspace.user.isSignedIn||Workspace.user.isAuthenticated){this.load();}}
FitQuestionnaireController.prototype.getAnswersMap=function(){
if(this.answerMap["BraSize"]!=undefined&&this.answerMap["BraSize"].indexOf(".")>-1){this.answerMap["CupSize"]=this.answerMap["BraSize"].split(".")[1];this.answerMap["BraSize"]=this.answerMap["BraSize"].split(".")[0];}
return this.answerMap;}
FitQuestionnaireController.prototype.setAnswersMap=function(answerMap,isSynchronizeWithServer){
if(answerMap!=undefined){if(answerMap["CupSize"]!=undefined&&answerMap["CupSize"]!=""){answerMap["BraSize"]=answerMap["BraSize"]+"."+answerMap["CupSize"];}
answerMap["VMName"]=undefined;
this.super_QuestionnaireController_setAnswersMap(answerMap,isSynchronizeWithServer);}}
FitQuestionnaireController.prototype.update=function(params){
if(this.isAllFieldsValid()){
params=(params!=undefined?params : new Array());
params[params.length]=["domain",this.domain];params[params.length]=["questionSet",this.questionSet];params[params.length]=["answers",MapUtils.toString(this.getAnswersMap(),"=",",")];
this.sendRequest("setAnswers",params);}else{this.updateFields();}}
FitQuestionnaireController.prototype.show=function(){
if(Workspace.user.isSignedIn&&!Workspace.user.isAuthenticated){Workspace.events.addEventScript(Workspace.events.EVENT_USER_AUTHENTICATED,this.id+".show()",true);Workspace.user.displayAuthentication();}else if(!this.isGenerated){
this.isGenerated=true;ParserUtils.applyTemplate(this.id+"_"+this.domain+"_Template",this.id+"Container",this,this.id+".initFields()");
if(Workspace.user.isAuthenticated){this.load();}}}
FitQuestionnaireController.prototype.onFieldFocus=function(fieldObject){
this.super_QuestionnaireController_onFieldFocus(fieldObject);
if(this.isAutomaticModelUpdate){if(fieldObject.name!="BirthyearNum"&&fieldObject.name!="HeightNum"){Model.requestModelInfo(undefined,{tapeMeasure:fieldObject.name});}else{Model.requestModelInfo();}}}
FitQuestionnaireController.prototype.onAnswersChange=function(){
Workspace.events.throwEvent(Workspace.events.EVENT_FIT_ATTRIBUTES_CHANGED,this);}
FitQuestionnaireController.prototype.catchEvent=function(eventKey,attributes){
this.super_QuestionnaireController_catchEvent(eventKey,attributes);
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED&&attributes.callingController==this&&attributes!=undefined&&attributes.response!=undefined&&attributes.action=="setAnswers"){
if(this.initialAnswersMap["BustNum"]!=undefined&&this.initialAnswersMap["BustNum"]==""){Workspace.events.throwEvent(Workspace.events.EVENT_FIT_CREATED,this);}}
if((eventKey==Workspace.events.EVENT_USER_SIGNIN&&Workspace.user.isAuthenticated)||eventKey==Workspace.events.EVENT_USER_AUTHENTICATED){this.load();}else if(eventKey==Workspace.events.EVENT_USER_SIGNOUT){this.setAnswersMap(this.defaultAnswersMap,false);this.onAnswersChange();}}
function ModelQuestionnaireController(id){jsClass.extend(this,[QuestionnaireController]);
this.id=id;this.domain=Workspace.population;}
ModelQuestionnaireController.prototype.questionSet="A";ModelQuestionnaireController.prototype.appearanceAdjustment=undefined;ModelQuestionnaireController.prototype.specialAppearance=undefined;ModelQuestionnaireController.prototype.isSubmitOnFieldChange=true;ModelQuestionnaireController.prototype.forcedAppearance=undefined;ModelQuestionnaireController.prototype.isRestoreAppearanceFromCookie=false;ModelQuestionnaireController.prototype.heightMappedBMIArray=undefined;ModelQuestionnaireController.prototype.MIN_BMI_VALUE=18;
ModelQuestionnaireController.prototype.init=function(){
this.handlerUrl=Workspace.serverContext+"/action/";this.super_QuestionnaireController_init();
this.defaultAnswersMap=this.defaultAnswersMap[Workspace.population];this.appearanceAdjustment=this.appearanceAdjustment[Workspace.population];this.answerMap=new Array();
if((Workspace.viewData["isAlreadyInitialized"]!="true"||Workspace.isPopulationChange)&&Workspace.viewData["isSignedIn"]!="true"){this.setAnswersMap(this.defaultAnswersMap);this.setDefaultAppearance();}
else{this.load();}}
ModelQuestionnaireController.prototype.setDefaultAppearance=function(){
if(Workspace.user.isSignedIn&&Workspace.user.isAuthenticated){this.load();}else if(!Workspace.user.isSignedIn){
var stateAppearance=(State.get("appearance")!=undefined?MapUtils.getMapFromString(decodeURIComponent(State.get("appearance"))): undefined);
if(this.forcedAppearance!=undefined){log.debug("using FORCED appearance for restoring model state",this);this.setAnswersMap(this.forcedAppearance,true);this.forcedAppearance=undefined;
}else if(stateAppearance!=undefined&&this.isRestoreAppearanceFromCookie){log.debug("using STATE appearance for restoring model state",this);this.setAnswersMap(stateAppearance,true);
}else if(Workspace.viewData["isAlreadyInitialized"]!="true"||Workspace.isPopulationChange){log.debug("using DEFAULT appearance for restoring model state",this);this.setAnswersMap(this.defaultAnswersMap,true);}
}else{}}
ModelQuestionnaireController.prototype.onAnswersChange=function(){
if(this.isRestoreAppearanceFromCookie){State.set("appearance",encodeURIComponent(new Map(this.getAnswersMap()).toString()));}
Workspace.events.throwEvent(Workspace.events.EVENT_MODEL_ATTRIBUTES_CHANGED,this);
}
ModelQuestionnaireController.prototype.getMetricHeightValue=function(){
return this.heightMappedBMIArray[this.fieldObjectMap["Height"].getValue()];}
ModelQuestionnaireController.prototype.sendRequest=function(actionType,params){
var requestParams=new Array();
requestParams=requestParams.concat(params);
det.sendRequest({serverUrl:this.handlerUrl+actionType,action:actionType,parameters:requestParams,callingController:this,group:"Model"});}
ModelQuestionnaireController.prototype.catchEvent=function(eventKey,attributes){
this.super_QuestionnaireController_catchEvent(eventKey,attributes);
if((eventKey==Workspace.events.EVENT_USER_SIGNIN&&Workspace.user.isAuthenticated)||eventKey==Workspace.events.EVENT_USER_AUTHENTICATED){this.load();}else if(eventKey==Workspace.events.EVENT_USER_SIGNOUT){this.restoreDefaultAnswers();}else if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED&&attributes.callingController==this){
if(attributes.response["missingAnswers"]!=undefined&&attributes.response["missingAnswers"]["required"]!=undefined){this.handleMobility(attributes.response);}}}
ModelQuestionnaireController.prototype.show=function(){
if(Workspace.user.isSignedIn&&!Workspace.user.isAuthenticated){Workspace.events.addEventScript(Workspace.events.EVENT_USER_AUTHENTICATED,this.id+".show()",true);Workspace.user.displayAuthentication();}else if(!this.isGenerated){this.isGenerated=true;ParserUtils.applyTemplate(this.id+"_"+this.domain+"_Template",this.id+"Container",this,this.id+".initFields()");
if(Workspace.user.isAuthenticated){this.load();}}}
ModelQuestionnaireController.prototype.handleMobility=function(attributes){
var requiredMissingAnswers=attributes["missingAnswers"]["required"];
for(var index in requiredMissingAnswers){this.fieldObjectMap[requiredMissingAnswers[index]].setInitialValue(this.defaultAnswersMap[requiredMissingAnswers[index]]);}
this.update();
Workspace.message.displayMessage(resource.get("missingAnswersMobilityCase"));}
ModelQuestionnaireController.prototype.adjustAppearance=function(bodySet){
bodySet=(bodySet==undefined?(Model.bodySet.join()=="REG"?"XR":"REG"): bodySet);
this.setAnswersMap(this.appearanceAdjustment[bodySet],true);
Workspace.events.addEventScript(Workspace.events.EVENT_MODEL_ATTRIBUTES_CHANGED,"Model.tryOnItems('"+Model.lastActionParameters["garmentsID"]+"')",true);}
ModelQuestionnaireController.prototype.isDefaultAppearance=function(){
var answerMap=this.getAnswersMap();var result=true;
for(var questionAnswerKey in this.defaultAnswersMap){
if(answerMap[questionAnswerKey]!=this.defaultAnswersMap[questionAnswerKey]&&questionAnswerKey!="VMName"){result=false;break;}}
return result;}
/**
* @class Controller that handles the creation/modification/deletion of the user profile
*
* @extends QuestionnaireController
* @param{Integer}idId of the instance
*
* Examples: welcome,new_password,... email as feedback for 
* profile-related events(EVENT_PROFILE_CREATED,EVENT_PROFILE_MODIFIED,...).
*
* event                 |emailReason|template
* EVENT_PROFILE_CREATED |Welcome    |EMailWelcomeTemplate.html
* EVENT_PROFILE_MODIFIED|Update     |EMailUpdateTemplate.html
*/
function ProfileQuestionnaireController(id){jsClass.extend(this,[QuestionnaireController]);
this.id=id;this.domain="AU";}
ProfileQuestionnaireController.prototype.questionSet="UP";ProfileQuestionnaireController.prototype.retailerNewsletterRegisterUrl="";ProfileQuestionnaireController.prototype.retailerNewsletterUnregisterUrl="";ProfileQuestionnaireController.prototype.isSendEmailForProfileCreatedEnabled=true;ProfileQuestionnaireController.prototype.isSendEmailForProfileModifiedEnabled=false;
ProfileQuestionnaireController.prototype.init=function(){
this.handlerUrl=Workspace.serverContext+"/action/";this.super_QuestionnaireController_init();}
ProfileQuestionnaireController.prototype.show=function(){
if(Workspace.user.isSignedIn&&!Workspace.user.isAuthenticated){Workspace.events.addEventScript(Workspace.events.EVENT_USER_AUTHENTICATED,this.id+".show()",true);Workspace.user.displayAuthentication();}else if(!this.isGenerated){this.isGenerated=true;
if(this.isSendEmailForProfileCreatedEnabled||this.isSendEmailForProfileModifiedEnabled){Workspace.activateController("EMail");}
ParserUtils.applyTemplate(this.id+"Template",this.id+"Container",this,this.id+".initFields()");
if(Workspace.user.isAuthenticated){this.load();}}}
ProfileQuestionnaireController.prototype.setAnswersMap=function(answerMap){
answerMap["RetypePassword"]=answerMap["Password"];
if(answerMap["RememberMe"]==undefined){answerMap["RememberMe"]=(Workspace.user.isRememberMeSettingActive?"true" : "false");}
this.super_QuestionnaireController_setAnswersMap(answerMap);}
ProfileQuestionnaireController.prototype.updateButtons=function(){
if(Workspace.user.isSignedIn){Anim.show(this.id+"DeleteButton");Anim.show(this.id+"SaveButton");Anim.hide(this.id+"CreateButton");}else{Anim.hide(this.id+"DeleteButton");Anim.hide(this.id+"SaveButton");Anim.show(this.id+"CreateButton");}
if(this.fieldObjectMap!=undefined&&this.fieldObjectMap["SigninName"]!=undefined){if(Workspace.user.isSignedIn){this.fieldObjectMap["SigninName"].disable();}else{this.fieldObjectMap["SigninName"].enable();}}}
ProfileQuestionnaireController.prototype.deleteProfile=function(isConfirmed){
if(Workspace.user.isSignedIn&&Workspace.user.isAuthenticated){
if(isConfirmed!=true){
this.callout=Workspace.message.displayMessage({"message":resource.get("Profile.Delete.Confirmation"),"templateId":"messageConfirmationTemplate","duration":0,"jsActionYes":this.id+".deleteProfile(true)","jsActionNo":"Workspace.message.hide('"+"messageObject"+Workspace.message.messageObjectCount+"')","isClosableOnClick":false});
}else{Workspace.showWait();this.sendRequest("deleteProfile",new Array());}}}
ProfileQuestionnaireController.prototype.onAnswersChange=function(){
this.updateButtons();
if(Workspace.user.isSignedIn){Workspace.events.throwEvent(Workspace.events.EVENT_PROFILE_UPDATED,this);}}
ProfileQuestionnaireController.prototype.save=function(){
var params=new Array();params[params.length]=["saveChanges","true"];
this.update(params);}
ProfileQuestionnaireController.prototype.catchEvent=function(eventKey,attributes){
this.super_QuestionnaireController_catchEvent(eventKey,attributes);
if((eventKey==Workspace.events.EVENT_USER_SIGNIN&&Workspace.user.isAuthenticated)||eventKey==Workspace.events.EVENT_USER_AUTHENTICATED){this.load();this.updateButtons();}else if(eventKey==Workspace.events.EVENT_USER_SIGNOUT){
this.setAnswersMap(this.defaultAnswersMap);this.updateButtons();
}else if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED&&attributes.callingController==this){
if(attributes.action=="setAnswers"&&attributes.response["suggestedUsernameInfo"]!=undefined){this.handleUsernameSuggestion(attributes.response["suggestedUsernameInfo"]);}else if(attributes.action=="deleteProfile"&&attributes.response["errorCode"]==undefined){Workspace.user.signout(true);
CookieUtils.deleteCookie("rememberMe");CookieUtils.deleteCookie("rememberMeCookie");Workspace.hideWait();Workspace.events.throwEvent(Workspace.events.EVENT_PROFILE_DELETED,this);}else if(attributes.action=="setAnswers"&&attributes.response["errorCode"]==undefined){
if(attributes.response["profileInfo"]!=undefined){
Workspace.events.throwEvent(Workspace.events.EVENT_PROFILE_CREATED,this);
if(this.isSendEmailForProfileCreatedEnabled){EMail.send("Welcome");}}else{
Workspace.events.throwEvent(Workspace.events.EVENT_PROFILE_MODIFIED,this);
if(this.isSendEmailForProfileModifiedEnabled){EMail.send("Update");}}
this.handleRememberMeCookie();this.onAnswersChange();}}}
/**
* Handles the setting/removal of the rememberMeCookie setting
*/
ProfileQuestionnaireController.prototype.handleRememberMeCookie=function(){
if(this.fieldObjectMap["RememberMe"].getValue()=="true"){Workspace.user.setRememberMeCookie(true);}else{Workspace.user.setRememberMeCookie(false);}}
/**
* Handles the registering/unregistering to the retailer newsletter
*/
ProfileQuestionnaireController.prototype.handleRetailerNewsletter=function(){
if(this.initialAnswersMap["NewsletterRetailer"]!=undefined||(this.fieldObjectMap["NewsletterRetailer"].getValue()!=this.initialAnswersMap["NewsletterRetailer"])){
if(this.fieldObjectMap["NewsletterRetailer"].getValue()=="true"){Workspace.callUrlIgnoreResponse(ParserUtils.parseHtml(this.retailerNewsletterRegisterUrl,this.getAnswersMap()));}else{Workspace.callUrlIgnoreResponse(ParserUtils.parseHtml(this.retailerNewsletterUnregisterUrl,this.getAnswersMap()));}}}
ProfileQuestionnaireController.prototype.handleUsernameSuggestion=function(attributes){
var fieldObject=this.fieldObjectMap["SigninName"];var content="";
Workspace.message.displayMessage({"templateId":"UsernameSuggestionTemplate","elementReference":(this.id+(this.domain!=""?"_"+this.domain : "")+"_"+fieldObject.name),"isClosableOnClick":false,"username": attributes["SUGGESTED_USER_NAMES"],"email": this.getAnswersMap()["Email"]});}
function QuestionnaireController(){log.error("QuestionnaireController: Cannot instanciate an interface");}
QuestionnaireController.prototype.id="QuestionnaireController";QuestionnaireController.prototype.fieldIdArray=undefined;QuestionnaireController.prototype.fieldObjectMap=undefined;QuestionnaireController.prototype.isInitialized=false;QuestionnaireController.prototype.isLoaded=false;QuestionnaireController.prototype.isGenerated=false;QuestionnaireController.prototype.isSubmitOnFieldChange=false;QuestionnaireController.prototype.handlerUrl=undefined;QuestionnaireController.prototype.questionSet="";QuestionnaireController.prototype.domain="";QuestionnaireController.prototype.callout=undefined;QuestionnaireController.prototype.initialAnswersMap=undefined;QuestionnaireController.prototype.defaultAnswersMap=undefined;QuestionnaireController.prototype.answerMap=undefined;QuestionnaireController.prototype.otherSetAnswersParams=undefined;
QuestionnaireController.prototype.init=function(){
this.initialAnswersMap=new Array();this.fieldIdArray=new Array();this.answerMap=new Array();
resource.applyProperties(this.id+"Properties",this);
Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);Workspace.events.addListener(Workspace.events.EVENT_USER_SIGNIN,this);Workspace.events.addListener(Workspace.events.EVENT_USER_AUTHENTICATED,this);Workspace.events.addListener(Workspace.events.EVENT_USER_SIGNOUT,this);
this.setAnswersMap(this.defaultAnswersMap);
Workspace.events.throwEvent(Workspace.events.EVENT_CONTROLLER_INITIALIZED,this);this.isInitialized=true;}
QuestionnaireController.prototype.show=function(){
if(!this.isGenerated){this.isGenerated=true;
ParserUtils.applyTemplate(this.id+"Template",this.id+"Container",this,this.id+".initFields()");}}
QuestionnaireController.prototype.setUnitSystem=function(unitSystem){
FieldUtils.setAllFieldsUnitSystem(this.fieldObjectMap,unitSystem,this);}
QuestionnaireController.prototype.isAllFieldsValid=function(){
return(this.fieldObjectMap!=undefined?FieldUtils.isAllFieldsValid(this.fieldObjectMap): true);}
QuestionnaireController.prototype.updateFields=function(){
FieldUtils.updateFields(this.fieldObjectMap);}
QuestionnaireController.prototype.onFieldChange=function(fieldObject){
if(fieldObject.isValid()==fieldObject.FIELD_VALID){this.answerMap[fieldObject.name]=fieldObject.getValue();}
if(this.isSubmitOnFieldChange){this.update();}
else{}
}
QuestionnaireController.prototype.onFieldFocus=function(fieldObject){
Workspace.message.hide(this.callout);
if(fieldObject.state!=fieldObject.FIELD_VALID&&fieldObject.isChanged()){var attributes=this.getCalloutAttributes(fieldObject);attributes["elementReference"]=this.id+(this.domain!=""?"_"+this.domain : "")+"_"+fieldObject.name;attributes["duration"]=5000;attributes["messageObjectId"]="fieldValidation";
if(fieldObject.isValid()!=FieldUtils.FIELD_VALID){this.callout=Workspace.message.displayMessage(attributes);}else{Workspace.message.hide(this.callout);}
}
}
QuestionnaireController.prototype.onFieldBlur=function(fieldObject){
Workspace.message.hide(this.callout);
}
QuestionnaireController.prototype.onAnswersChange=function(){}
QuestionnaireController.prototype.getCalloutHTML=function(fieldObject){
var attributes=new Array();attributes["message"]=fieldObject.getErrorMessage();
return ParserUtils.parseTemplate("calloutTemplate",attributes);}
QuestionnaireController.prototype.getCalloutAttributes=function(fieldObject){
var attributes=new Array();attributes["message"]=fieldObject.getErrorMessage();attributes["templateId"]="calloutTemplate";
return attributes;}
QuestionnaireController.prototype.load=function(){
this.sendRequest(
"getAnswers",[["domain",this.domain],["questionSet",this.questionSet]])}
QuestionnaireController.prototype.save=function(){
var params=new Array();
if(Workspace.user.isSignedIn){params[params.length]=["saveChanges","true"];}
this.update(params);}
QuestionnaireController.prototype.getAnswersMap=function(){
return MapUtils.getClone(this.answerMap);}
QuestionnaireController.prototype.setAnswersMap=function(answerMap,isSynchronizeWithServer){
isSynchronizeWithServer=(isSynchronizeWithServer!=undefined?isSynchronizeWithServer : false);
for(var key in answerMap){if(key!=undefined&&answerMap[key]!=undefined){this.answerMap[key]=answerMap[key];}}
if(this.isGenerated){FieldUtils.setAllFieldsAnswers(this.fieldObjectMap,this.answerMap);}
if(isSynchronizeWithServer){this.save();}}
QuestionnaireController.prototype.clear=function(){
var emptyMap=new Array();
for(var fieldId in this.fieldObjectMap){emptyMap[fieldId]="";}
this.setAnswersMap(emptyMap,true);}
QuestionnaireController.prototype.reset=function(){
this.setAnswersMap(this.initialAnswersMap,true);}
QuestionnaireController.prototype.initFields=function(){
this.initialAnswersMap=MapUtils.getClone(this.answerMap);
this.fieldObjectMap=FieldUtils.initFieldsList(
this.answerMap,this,this.id+(this.domain!=""?"_"+this.domain : ""));}
QuestionnaireController.prototype.update=function(params){
var answers=MapUtils.toString(this.getAnswersMap(),"=",",");
if(this.isAllFieldsValid()&&answers!=""){
params=(params!=undefined?params : new Array());
params[params.length]=["domain",this.domain];params[params.length]=["questionSet",this.questionSet];params[params.length]=["answers",answers];
if(this.otherSetAnswersParams!=undefined){for(var key in this.otherSetAnswersParams){params[params.length]=[key,this.otherSetAnswersParams[key]];}}
Workspace.showWait();
this.sendRequest("setAnswers",params);
}else{
if(resource.get(this.id+"_invalidInput")!=""){Workspace.message.displayMessage(resource.get(this.id+"_invalidInput"));}
this.updateFields();
}}
QuestionnaireController.prototype.restoreDefaultAnswers=function(){
this.answerMap=new Array();this.setAnswersMap(this.defaultAnswersMap,true);FieldUtils.setAllFieldsUnchanged(this.fieldObjectMap);}
QuestionnaireController.prototype.restoreInitialAnswers=function(){
this.answerMap=new Array();this.setAnswersMap(this.initialAnswersMap,true);FieldUtils.setAllFieldsUnchanged(this.fieldObjectMap);}
QuestionnaireController.prototype.sendRequest=function(actionType,params){
var requestParams=new Array();
requestParams=requestParams.concat(params);
det.sendRequest({serverUrl:this.handlerUrl+actionType,action:actionType,parameters:requestParams,callingController:this});}
QuestionnaireController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED&&attributes.callingController==this){if(attributes!=undefined&&attributes.response!=undefined){
if(attributes.action=="setAnswers"&&attributes.response["errorCode"]==undefined){this.initialAnswersMap=MapUtils.getClone(this.answerMap);this.onAnswersChange();Workspace.hideWait();}
if(attributes.response["answers"]!=undefined){this.setAnswersMap(attributes.response["answers"]);this.onAnswersChange();Workspace.hideWait();this.isLoaded=true;}}}}
function SigninQuestionnaireController(id){jsClass.extend(this,[QuestionnaireController]);
this.id=id;this.domain="";}
SigninQuestionnaireController.prototype.questionSet="";SigninQuestionnaireController.prototype.onForgotPasswordSuccessful=undefined;
SigninQuestionnaireController.prototype.init=function(){
this.handlerUrl=Workspace.serverContext+"/action/";this.super_QuestionnaireController_init();}
SigninQuestionnaireController.prototype.load=function(){}
SigninQuestionnaireController.prototype.show=function(){
var answers={"SigninName":Workspace.user.username,"Password":"","RememberMe":(Workspace.user.isRememberMeSettingActive?"true":"false"),"HintQuestion":"","HintAnswer":"","Email":""}
this.setAnswersMap(answers);
if(!this.isGenerated){this.isGenerated=true;
ParserUtils.applyTemplate(this.id+"Template",this.id+"Container",this,this.id+".initFields()");}else{Anim.reset("SigninQuestionnaireForgotPassword",undefined,true);}}
SigninQuestionnaireController.prototype.hide=function(){
Anim.reset("SigninQuestionnaireForgotPassword",undefined,true);Anim.reset(this.id+"Panel");}
SigninQuestionnaireController.prototype.showForgotPassword=function(){
var answers=this.getAnswersMap();
if(answers["SigninName"]!=""&&this.fieldObjectMap["SigninName"].isValid()==FieldUtils.FIELD_VALID){
this.sendRequest("getSecretQuestion",MapUtils.toArray(answers));}else{Workspace.message.displayMessage(resource.get("Signin.ForgotPassword.UsernameRequired"));}}
SigninQuestionnaireController.prototype.submit=function(){
var answers=this.getAnswersMap();
if(answers["SigninName"]!=""&&answers["Password"]!=""&&this.fieldObjectMap["SigninName"].isValid()==FieldUtils.FIELD_VALID&&this.fieldObjectMap["Password"].isValid()==FieldUtils.FIELD_VALID){
Workspace.user.signin(answers);
}else{FieldUtils.updateField(this.fieldObjectMap["SigninName"]);FieldUtils.updateField(this.fieldObjectMap["Password"]);}}
SigninQuestionnaireController.prototype.submitForgotPassword=function(){
var answers=this.getAnswersMap();
if(answers["SigninName"]!=""&&answers["HintAnswer"]!=""&&answers["Email"]!=""&&this.fieldObjectMap["SigninName"].isValid()==FieldUtils.FIELD_VALID&&this.fieldObjectMap["HintAnswer"].isValid()==FieldUtils.FIELD_VALID&&this.fieldObjectMap["Email"].isValid()==FieldUtils.FIELD_VALID){
Workspace.user.signin(answers,true);
}else{this.fieldObjectMap["Password"].isFieldChanged=false;FieldUtils.updateField(this.fieldObjectMap["SigninName"]);FieldUtils.updateField(this.fieldObjectMap["HintAnswer"]);FieldUtils.updateField(this.fieldObjectMap["Email"]);
for(var fieldId in this.fieldObjectMap){
if(this.fieldObjectMap[fieldId].isValid()!=FieldUtils.FIELD_VALID){this.onFieldFocus(this.fieldObjectMap[fieldId]);break;}}}}
SigninQuestionnaireController.prototype.sendRequest=function(actionType,params){
var requestParams=new Array();
requestParams=requestParams.concat(params);
det.sendRequest({serverUrl:this.handlerUrl+actionType,action:actionType,parameters:requestParams,callingController:this});}
SigninQuestionnaireController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED){if(attributes!=undefined&&attributes.response!=undefined){
if(attributes.action=="signInPassword"&&attributes.response["errorCode"]==undefined){
var answers=this.getAnswersMap();if(answers["RememberMe"]!=undefined){Workspace.user.setRememberMeCookie((answers["RememberMe"]=="true"?true : false))}
this.hide();
}else if(attributes.action=="signInAnswer"&&attributes.response["errorCode"]==undefined){this.hide();
if(this.onForgotPasswordSuccessful!=undefined){eval(this.onForgotPasswordSuccessful);}
}else if(attributes.action=="getSecretQuestion"&&attributes.response["errorCode"]==undefined){
if(attributes.response["HintQuestion"]!=undefined){document.getElementById("SigninQuestionnaire_HintQuestion").innerHTML=resource.get("HintQuestions")[attributes.response["HintQuestion"]];
Anim.openSingle("SigninQuestionnaireForgotPassword");}
}else if(attributes.action=="signInPassword"&&attributes.response["errorCode"]=="FS-19000"){Workspace.message.displayMessage({message:resource.get("IDTP-02003")});}}}}
var defaultProductResourceMap={
"Vdr.Favorites.NotSignedIn":"<b>We're sorry...</b><br>You need to register before using My Favorites. You can either<strong>sign in</strong>to a previously saved profile,or click<strong>My Account</strong>to create your own user profile now.","Vdr.ModelSave.NotSignedIn":"In order to save your model for later use,you need to create a profile.<br><br>Do you want to go to the profile creation page?","MSG_AUTHENTICATION":"<b>We're sorry...</b><br>You need to authenticate yourself before using My Favorites. Please<strong>sign in</strong>using your profile.","Vdr.Favorites.NoFavoriteItems":"There are currently no saved items in My Favorites.","Vdr.Favorites.NoFavoriteOutfits":"There are currently no saved outfits in My Favorites.","Vdr.Favorites.AddToFavoritesFromExternalSuccess":"This item/room has been saved to My Favorites.","Vdr.Favorites.confirmDeleteItem":"Are you sure you want to delete this item from your favorites?","Vdr.Favorites.confirmDeleteOutfit":"Are you sure you want to delete this outfit from your favorites?","Vdr.Favorites.Removed":"This item/outfit was successfully removed from your favorites.","ItemAlreadyExist":"This item has been saved already.","OutfitAlreadyExist":"This outfit has been saved already.","Vdr.Category.Empty":"No items are available in this category"
,"Questionnaire.Field.SigninName.Label":"USERNAME","Questionnaire.Field.Password.Label":"PASSWORD","Questionnaire.Field.RetypePassword.Label":"RETYPE PASSWORD","Questionnaire.Field.RememberMe.Label":"","Questionnaire.Field.HintQuestion.Label":"HINT QUESTION","Questionnaire.Field.HintAnswer.Label":"HINT ANSWER","Questionnaire.Field.Email.Label":"E-MAIL ADDRESS","Questionnaire.Field.PCode.Label":"ZIP CODE","Questionnaire.Field.NewsletterRetailer.Label":"","Questionnaire.Field.NewsLetter.Label":"","Questionnaire.ErrorMessage.InvalidField":"Please review the answers beside the red stars below: ","Questionnaire.ErrorMessage.InvalidLength":"Your answer must be between @minLength@ and @maxLength@ character(s).","Questionnaire.ErrorMessage.InvalidMinLength":"Your answer must be at least @minLength@ character(s)long.","Questionnaire.ErrorMessage.InvalidMaxLength":"Your answer must be at most @maxLength@ character(s)long.","Questionnaire.ErrorMessage.Required":"Your answer is required.","Questionnaire.ErrorMessage.InvalidCharacters":"Your answer contains invalid characters.","Questionnaire.ErrorMessage.InvalidEmail":"Your answer is not a valid e-mail address.","Questionnaire.ErrorMessage.InvalidNumeric":"Your answer is not a valid numeric value.","Questionnaire.ErrorMessage.InvalidRange":"Please type a number between [$('@measurementSystem@'=='METRIC'?parseInt(@minValue@ * 0.4535):('@measurementSystem@'=='IMPERIALSTONES'?parseInt(@minValue@ * 0.07143):@minValue@))$] and [$('@measurementSystem@'=='METRIC'?parseInt(@maxValue@ * 0.4535):('@measurementSystem@'=='IMPERIALSTONES'?parseInt(@maxValue@ * 0.07143):@maxValue@))$] @units@.","Questionnaire.ErrorMessage.InvalidMinRange":"Please type a number greater than @minValue@.","Questionnaire.ErrorMessage.InvalidMaxRange":"Please type a number less than @maxValue@.","Questionnaire.ErrorMessage.PasswordDontMatch":"Your passwords do not match.","Questionnaire.ErrorMessage.BustOrBraRequired":"Please,provide either your bust measurement or bra size.","Questionnaire.ErrorMessage.BmiReajusted":"We readjusted your weight to meet our minimum BMI(Body Mass Index).","Questionnaire.Field.PleaseSelectOne":"Please select one"
,"Profile.Delete.Confirmation":"Are you sure you wish to delete your profile?","Profile.Create.Confirmaton":"Your profile was created successfully.","Signin.ForgotPassword.UsernameRequired":"In order to reset your password,please enter your username first.","Signin.RememberMeCookie.RemoveAtSignout":"Do you wish to be remembered next time you visit a My Virtual Model affiliated site?"
,"History.RemovedItems.Explanation":"One or many items were removed and put in the History list."
,"ECard.confirmation":"Your message is on its way!","Weightloss.InvalidGoalWeight":"Your goal weight must be equal or lower than your current weight.","Weightloss.BMIGoalWeightReajusted":"We reajusted your weight goal to meet the minimum BMI of 18"
,"HelpTechnicalSupport.confirmation":"Your message is on its way.<br><br>We will answer as soon as possible."
,"missingAnswersMobilityCase":"Your model was automatically updated to use this site. Please update your model.","Model.Content.IncompatibleItemRemoved":"Some items are incompatible with your model and have been removed.","Model.Content.IncompatibleItemTryon":"This item is not available for your model.","Model.Content.AlternateItemTryon":"The item you tried on is not available for your model,but an alternate item was used instead.","Model.Weightloss.IncompatibleItemRemoved":"Some items are incompatible with your<b>weightloss</b>model and have been removed.","cookiesNotSupported":"Sorry,You must enable cookies before using this service. Please,set your Security and Privacy preferences to Medium(Default settings).","Fit.Rating.Loading":"Calculating Fit Rating... Please wait","MyContent.Delete.Confirmation":"Are you sure you wish to delete this content?","MyContent.ContentDeleted":"Your content has been successfully deleted.","MyContent.Context.LimitPerImageReached":"Sorry,you've already reached the limit of context per image","MyContent.Upload.Unsupported":"Sorry,this media file is not supported.","MyContent.Upload.Uploading":"Uploading media. Please wait..."
,"SigninAlreadyExist":"This username is already registered. Please type in a different username.","Signin.DoesNotExist":"This username does not exist. Please type in a different username.","BUSINESS DELEGATE.UnexpectedError":"Sorry...<br><br>An unexpected error has occured. Please try again later.","couldNotFindMappingForExternalTryOn":"Sorry...<br><br>The selected item is not found.","noGarmentFoundError":"Sorry...<br><br>The selected item is not found.","fileSizeTooBig":"The size of the media you attempted to upload is too large. Please try again with a smaller file.","invalidImageFormat":"Unsupported file format. Please use a compatible file format as JPEG,PNG","userNotSignedIn":"You need to be signed in with your My Virtual ID to use this feature.","CannotCreateSignin":"You need to be signed in with your MyVirtualID to use this feature.","noEnoughFreeSpace":"You have used all your available free space for your account. Please remove un-needed media or content,and start again","requestInvalid":"Unable to process this request. Please try again later.","RetailerCodeNotFound":"Retailer code not found."
,"Signin.InvalidUserPassword":"Invalid username and password combination. Please,try again.<br><br>Note: Make sure to use the same capitalization as saved in your profile.","Signin.InvalidForgotPassword":"Wrong hint answer or e-mail address. Please,try again."
,"BUSINESS DELEGATE.RemsSystemError":"Sorry...<br><br>An error occured when adding this item in the scene.","fitMissingDimension":"A fit measurement is missing. Please enter the measurement to get a fit evaluation."
,"ProfileQuestionnaire_invalidInput":"There is one or more invalid answers in your profile,please review."
,"ModelQuestionnaireUnitSuffixMap":{"IMPERIAL":{"major":"feet","minor":"inches"},"IMPERIALSTONES":{"major":"feet","minor":"inches"},"METRIC":{"major":"m","minor":"cm"}}
,"FudgeFactorAnswers":[4900,4901,4902],"AgeGroupAnswers":[2512,2511],"EyeShapeAnswers":[2212,2211],"NoseShapeAnswers":[2802,2801],"LipShapeAnswers":[2901,2902]
,"WomenEthnicAnswers":[1451,1455,1454,1450,1453,1452],"WomenBodyShapeAnswers":[2813,2812,2811],"WomenBustCupAnswers":{"811":"small-medium","812":"medium-large"},"WomenWaistShapeAnswers":{"512":"undefined","511":"well-defined"},"WomenHairColorAnswers":[2012,2016,2013,2015,2011,2014],"WomenHairStyleAnswers":[2115,2112,2111,2127,2128,2124,2123,2122,2120,2119,2118,2116],"WomenHairStyle_F_40Answers":[2115,2114,2112,2111,2124,2123,2122,2121,2120,2119,2118,2116],"WomenHeightAnswers":{"IMPERIAL":{"3529":"4' 10&quot;or less","3511":"4' 11&quot;","3512":"5'","3513":"5' 1&quot;","3514":"5' 2&quot;","3515":"5' 3&quot;","3516":"5' 4&quot;","3517":"5' 5&quot;","3518":"5' 6&quot;","3519":"5' 7&quot;","3520":"5' 8&quot;","3521":"5' 9&quot;","3522":"5' 10&quot;","3523":"5' 11&quot;","3524":"6'","3525":"6' 1&quot;","3526":"6' 2&quot;","3527":"6' 3&quot;","3528":"6' 4&quot;and up"},"IMPERIALSTONES":{"3529":"4' 10&quot;or less","3511":"4' 11&quot;","3512":"5'","3513":"5' 1&quot;","3514":"5' 2&quot;","3515":"5' 3&quot;","3516":"5' 4&quot;","3517":"5' 5&quot;","3518":"5' 6&quot;","3519":"5' 7&quot;","3520":"5' 8&quot;","3521":"5' 9&quot;","3522":"5' 10&quot;","3523":"5' 11&quot;","3524":"6'","3525":"6' 1&quot;","3526":"6' 2&quot;","3527":"6' 3&quot;","3528":"6' 4&quot;and up"},"METRIC":{"3529":"1,47 m or less","3511":"1,49 or 1,51 m","3512":"1,53 m","3513":"1,55 m","3514":"1,57 m","3515":"1,59 or 1,61 m","3516":"1,63 m","3517":"1,65 m","3518":"1,67 or 1,69 m","3519":"1,71 m","3520":"1,73 m","3521":"1,75 m","3522":"1,77 or 1,79 m","3523":"1,81 m","3524":"1,83 m","3525":"1,85 m","3526":"1,87 or 1,89 m","3527":"1,91 m","3528":"1,93 m or more"}}
,"MenEthnicAnswers":[1451,1450,1453,1452],"MenBeardStyleAnswers":[3001,3002,3003,3004],"MenBeardColorAnswers":[3102,3106,3103,3105,3101,3104],"MenSideViewShapeAnswers":[4311,4312],"MenBuildAnswers":{"5101":"Regular","5102":"Muscular"},"MenShoulderWidthAnswers":{"311":"Narrower","312":"Broader"},"MenHairColorAnswers":[2012,2016,2013,2015,2011,2014],"MenHairStyleAnswers":[2131,2132,2133,2134,2135,2136,2137,2138,2139,2140,2141,2142],"MenHairStyle_M_30Answers":[2131,2132,2133,2134,2135,2136,2137,2138,2139,2140,2141,2142],"MenHeightAnswers":{"IMPERIAL":{"3529":"4' 10&quot;or less","3511":"4' 11&quot;","3512":"5'","3513":"5' 1&quot;","3514":"5' 2&quot;","3515":"5' 3&quot;","3516":"5' 4&quot;","3517":"5' 5&quot;","3518":"5' 6&quot;","3519":"5' 7&quot;","3520":"5' 8&quot;","3521":"5' 9&quot;","3522":"5' 10&quot;","3523":"5' 11&quot;","3524":"6'","3525":"6' 1&quot;","3526":"6' 2&quot;","3527":"6' 3&quot;","3528":"6' 4&quot;and up"},"IMPERIALSTONES":{"3529":"4' 10&quot;or less","3511":"4' 11&quot;","3512":"5'","3513":"5' 1&quot;","3514":"5' 2&quot;","3515":"5' 3&quot;","3516":"5' 4&quot;","3517":"5' 5&quot;","3518":"5' 6&quot;","3519":"5' 7&quot;","3520":"5' 8&quot;","3521":"5' 9&quot;","3522":"5' 10&quot;","3523":"5' 11&quot;","3524":"6'","3525":"6' 1&quot;","3526":"6' 2&quot;","3527":"6' 3&quot;","3528":"6' 4&quot;and up"},"METRIC":{"3529":"1,47 m or less","3511":"1,49 or 1,51 m","3512":"1,53 m","3513":"1,55 m","3514":"1,57 m","3515":"1,59 or 1,61 m","3516":"1,63 m","3517":"1,65 m","3518":"1,67 or 1,69 m","3519":"1,71 m","3520":"1,73 m","3521":"1,75 m","3522":"1,77 or 1,79 m","3523":"1,81 m","3524":"1,83 m","3525":"1,85 m","3526":"1,87 or 1,89 m","3527":"1,91 m","3528":"1,93 m or more"}}
,"WomenBraSizeAnswers":{"IMPERIAL":{"30.0":"30AA","30.1":"30A","32.0":"32AA","32.1":"32A","32.2":"32B","32.3":"32C","34.1":"34A","34.2":"34B","34.3":"34C","34.4":"34D","34.5":"34DD","36.1":"36A","36.2":"36B","36.3":"36C","36.4":"36D","36.5":"36DD","36.6":"36E","36.7":"36F","36.8":"36H","38.2":"38B","38.3":"38C","38.4":"38D","38.5":"38DD","38.6":"38E","38.7":"38F","38.8":"38G","38.9":"38H","40.2":"40B","40.2":"40B","40.3":"40C","40.4":"40D","40.5":"40DD","40.6":"40E","40.7":"40F","40.8":"40G","40.9":"40H","40.10":"40I","42.2":"42B","42.3":"42C","42.4":"42D","42.5":"42DD","42.6":"42E","42.7":"42F","42.8":"42G","42.9":"42H","42.10":"42I","44.2":"44B","44.3":"44C","44.4":"44D","44.5":"44DD","44.6":"44E","44.7":"44F","44.8":"44G","44.9":"44H","44.10":"44I","46.2":"46B","46.3":"46C","46.4":"46D","46.5":"46DD","46.6":"46E","46.7":"46F","46.8":"46G","46.9":"46H","46.10":"46I","48.2":"48B","48.3":"48C","48.4":"48D","48.5":"48DD","48.6":"48E","48.7":"48F","48.8":"48G","48.9":"48H","48.10":"48I","50.2":"50B","50.3":"50C","50.4":"50D","50.5":"50DD","50.6":"50E","50.7":"50F","50.8":"50G","50.9":"50H","50.10":"50I","52.2":"52B","52.3":"52C","52.4":"52D","52.5":"52DD","52.6":"52E","52.7":"52F","52.8":"52G","52.9":"52H","52.10":"52I"},"IMPERIALSTONES":{"30.0":"30AA","30.1":"30A","32.0":"32AA","32.1":"32A","32.2":"32B","32.3":"32C","34.1":"34A","34.2":"34B","34.3":"34C","34.4":"34D","34.5":"34DD","36.1":"36A","36.2":"36B","36.3":"36C","36.4":"36D","36.5":"36DD","36.6":"36E","36.7":"36F","36.8":"36H","38.2":"38B","38.3":"38C","38.4":"38D","38.5":"38DD","38.6":"38E","38.7":"38F","38.8":"38G","38.9":"38H","40.2":"40B","40.2":"40B","40.3":"40C","40.4":"40D","40.5":"40DD","40.6":"40E","40.7":"40F","40.8":"40G","40.9":"40H","40.10":"40I","42.2":"42B","42.3":"42C","42.4":"42D","42.5":"42DD","42.6":"42E","42.7":"42F","42.8":"42G","42.9":"42H","42.10":"42I","44.2":"44B","44.3":"44C","44.4":"44D","44.5":"44DD","44.6":"44E","44.7":"44F","44.8":"44G","44.9":"44H","44.10":"44I","46.2":"46B","46.3":"46C","46.4":"46D","46.5":"46DD","46.6":"46E","46.7":"46F","46.8":"46G","46.9":"46H","46.10":"46I","48.2":"48B","48.3":"48C","48.4":"48D","48.5":"48DD","48.6":"48E","48.7":"48F","48.8":"48G","48.9":"48H","48.10":"48I","50.2":"50B","50.3":"50C","50.4":"50D","50.5":"50DD","50.6":"50E","50.7":"50F","50.8":"50G","50.9":"50H","50.10":"50I","52.2":"52B","52.3":"52C","52.4":"52D","52.5":"52DD","52.6":"52E","52.7":"52F","52.8":"52G","52.9":"52H","52.10":"52I"},"METRIC":{"30.0":"65AA","30.1":"65A","32.0":"70AA","32.1":"70A","32.2":"70B","32.3":"70C","34.1":"75A","34.2":"75B","34.3":"75C","34.4":"75D","34.5":"75DD","36.1":"80A","36.2":"80B","36.3":"80C","36.4":"80D","36.5":"80DD","36.6":"80E","36.7":"80F","36.8":"80H","38.2":"85B","38.3":"85C","38.4":"85D","38.5":"85DD","38.6":"85E","38.7":"85F","38.8":"85G","38.9":"85H","40.2":"90B","40.2":"90B","40.3":"90C","40.4":"90D","40.5":"90DD","40.6":"90E","40.7":"90F","40.8":"90G","40.9":"90H","40.10":"90I","42.2":"95B","42.3":"95C","42.4":"95D","42.5":"95DD","42.6":"95E","42.7":"95F","42.8":"95G","42.9":"95H","42.10":"95I","44.2":"100B","44.3":"100C","44.4":"100D","44.5":"100DD","44.6":"100E","44.7":"100F","44.8":"100G","44.9":"100H","44.10":"100I","46.2":"105B","46.3":"105C","46.4":"105D","46.5":"105DD","46.6":"105E","46.7":"105F","46.8":"105G","46.9":"105H","46.10":"105I","48.2":"110B","48.3":"110C","48.4":"110D","48.5":"110DD","48.6":"110E","48.7":"110F","48.8":"110G","48.9":"110H","48.10":"110I","50.2":"115B","50.3":"115C","50.4":"115D","50.5":"115DD","50.6":"115E","50.7":"115F","50.8":"115G","50.9":"115H","50.10":"115I","52.2":"120B","52.3":"120C","52.4":"120D","52.5":"120DD","52.6":"120E","52.7":"120F","52.8":"120G","52.9":"120H","52.10":"120I"},"fr_FR":{"30.0":"80AA","30.1":"80A","32.0":"85AA","32.1":"85A","32.2":"85B","32.3":"85C","34.1":"90A","34.2":"90B","34.3":"90C","34.4":"90D","34.5":"90DD","36.1":"95A","36.2":"95B","36.3":"95C","36.4":"95D","36.5":"95DD","36.6":"95E","36.7":"95F","36.8":"95H","38.2":"100B","38.3":"100C","38.4":"100D","38.5":"100DD","38.6":"100E","38.7":"100F","38.8":"100G","38.9":"100H","40.2":"105B","40.2":"105B","40.3":"105C","40.4":"105D","40.5":"105DD","40.6":"105E","40.7":"105F","40.8":"105G","40.9":"105H","40.10":"105I","42.2":"110B","42.3":"110C","42.4":"110D","42.5":"110DD","42.6":"110E","42.7":"110F","42.8":"110G","42.9":"110H","42.10":"110I","44.2":"115B","44.3":"115C","44.4":"115D","44.5":"115DD","44.6":"115E","44.7":"115F","44.8":"115G","44.9":"115H","44.10":"115I","46.2":"46B","46.3":"46C","46.4":"46D","46.5":"46DD","46.6":"46E","46.7":"46F","46.8":"46G","46.9":"46H","46.10":"46I","48.2":"120B","48.3":"120C","48.4":"120D","48.5":"120DD","48.6":"120E","48.7":"120F","48.8":"120G","48.9":"120H","48.10":"120I","50.2":"125B","50.3":"125C","50.4":"125D","50.5":"125DD","50.6":"125E","50.7":"125F","50.8":"125G","50.9":"125H","50.10":"125I","52.2":"130B","52.3":"130C","52.4":"130D","52.5":"130DD","52.6":"130E","52.7":"130F","52.8":"130G","52.9":"130H","52.10":"130I"}}
,"WomenBreastShapeAnswers":{1:"Shallow",2:"Average",3:"Full"}
,"MeasurementSuffix":{"IMPERIAL":"inches","IMPERIALSTONES":"inches","METRIC":"cm"}
,"WeightSuffix":{"IMPERIAL":"pounds","IMPERIALSTONES":"stones|pounds","METRIC":"kg"}
,"BirthYearSuffix":{"IMPERIAL":"years","IMPERIALSTONES":"years","METRIC":"years"}
,"HintQuestions":{"712":"Favorite animal?","711":"Mother's maiden name?","719":"Favorite movie?","718":"Childhood hero?","717":"Make of first car/bike?","716":"Favorite teacher?","715":"Best friend's name?","714":"Place of birth?","713":"Favorite restaurant?"}
,"WorkspaceProperties":{"fatalErrorCodes":"FS-01001,MVM-00001,MVM-01001,FS-01015,ConfigManagerError","isDisplaySplash":true,"libServerUrl":""}
,"ControllerSelection":{"Items":"ItemCacheController","ModelAppearance":"ModelAppearanceController","ModelQuestionnaire":"ModelQuestionnaireController","Model":"ModelController","OnMyModel":"OnMyModelController","ModelMap":"ModelMapController","Catalog":"CatalogDropdownController","CatalogFilter":"FilterController","CatalogCategory":"CatalogCategoryController","RoomConfig":"ConfigController","Favorites":"FavoritesController","ModelView":"ModelViewController","RemovedItemHistory":"RemovedItemHistoryController","FitQuestionnaire":"FitQuestionnaireController","SigninQuestionnaire":"SigninQuestionnaireController","ProfileQuestionnaire":"ProfileQuestionnaireController","ECard":"ECardController","EMail":"EMailController","FitTag":"FitRatingController","FitDetails":"FitRatingController","Help":"HelpController","Remote":"RemoteController","StorageSolutions":"StorageSolutionsController","Media":"MediaController","FaceMapping":"FaceMappingController","Tracer":"TracerController","ColorShift":"ColorShiftController","ColorAdjust":"ColorAdjustController","MoveResize":"MoveResizeController","MyContent":"MyContentController","Crop":"CropController","DragDrop":"DragDropController","Overlay":"OverlayController","Tracker":"TrackerController","CameraControl":"CameraController","UnitTest":"UnitTestController"}
,"ClassDependency":{"CatalogDropdownController":"CatalogController","CatalogStickController":"CatalogController","FilterPopupController":"FilterController","RoomConfigController":"ConfigController","RemovedItemHistoryController":"HistoryController","FitQuestionnaireController":"QuestionnaireController","ProfileQuestionnaireController":"QuestionnaireController","SigninQuestionnaireController":"QuestionnaireController","ModelQuestionnaireController":"QuestionnaireController","ECardController":"QuestionnaireController","HelpController":"QuestionnaireController","MyContentController":"MediaController,DragDropController","FaceMappingController":"WizardController","OverlayController":"WizardController","VisualSearchController":"ViewportController","ModelCSController":"ModelRenderController","ModelMPSController":"ModelRenderController","ModelController":"Camera","ModelController":"ModelContentController"}
,"ControllerInitOrder":[
"Items","Remote","ModelAppearance","ModelQuestionnaire"
,"Model","CatalogCategory"
]
,"ModelProperties":{"viewId":1,"viewCount":{"0":6},"compositorAlgorithm":"1","compositorQuality":"090","compositorMapVersion":"2","isZoomFeatureEnabled":false,"defaultBackgroundImageArray":[],"layoutId":0,"isRestoreWornGarmentsFromCookie":true,"defaultImageSource":"SMALL_IMAGE","imageWidth":450,"imageHeight":360,"largeImageWidth":900,"largeImageHeight":720,"layoutIdArray":[0],"isAutomaticBestView":false,"zoomFactor":2,"alternateItemAutoTryon":true,"compositorBrightness":"","compositorContrast":"","compositorGamma":"","defaultType":"","drMode":"","isDisplayMouseOverCallout":true,"isDisplayMouseDownCallout":true}
,"ModelViewProperties":{}
,"ModelMapProperties":{"multiplePolygonColors":["cyan","red","blue","yellow","green","cyan","red","blue","yellow","green","cyan","red","blue","yellow","green","cyan","red","blue","yellow","green"],"isDrawPolygons":false}
,"CatalogProperties":{"elementId":"CatalogPanel","categoryElementId":"sectionSelectAnItemCategories","isDisplayOutfits":true,"isDisplayItems":true,"isOpenDefaultCategoryAtStartup":false,"isRemoveIncompatibleItems":true,"thumbnailPrefix":"","thumbnailSuffix":""}
,"CatalogCategoryProperties":{"rootCategoryId":""}
,"OnMyModelProperties":{"thumbnailPrefix":"","thumbnailSuffix":"","swatchUrl":"","isRemoveIncompatibleItems":false,"buyOutfitUrlTemplate":"/buyoutfit?sid=[$Workspace.query.sid$][FOR_EACH(Model.content.wornGarmentMap)$&param1=@CLIENT_DATA/0/PARAM1@&param2=@CLIENT_DATA/0/PARAM2@&param3=@CLIENT_DATA/0/PARAM3@$FOR_EACH(Model.content.wornGarmentMap)]"}
,"FavoritesProperties":{"thumbnailPrefix":"","thumbnailSuffix":"","outfitThumbnailWidth":"280","outfitThumbnailHeight":"224","isRemoveIncompatibleItems":false}
,"ModelQuestionnaireProperties":{
"defaultAnswersMap":{"F":{"Ethnic":"1450","FudgeFactor":"4901","BodyShape":"2811","NoseShape":"2801","WeightNum":"144","BustCup":"812","LipShape":"2902","HairStyle_F_40":"2123","WaistShape":"511","VMName":"Default Women Model","HairColor":"2015","AgeGroup":"2512","EyeShape":"2211","Height":"3518"},"M":{"HairStyle_M_30":"2132","BeardColor":"3105","EyeShape":"2211","Ethnic":"1450","Build":"5101","NoseShape":"2802","WeightNum":"205","LipShape":"2901","Height":"3521","ShoulderWidth":"311","SideViewShape":"4312","VMName":"Default Men Model","FudgeFactor":"4902","HairColor":"2015","BeardStyle":"3002","AgeGroup":"2511"}}
,"appearanceAdjustment":{"F":{"REG":{"WeightNum":"166","Height":"3519","FudgeFactor":"4901"},"XR":{"WeightNum":"220","Height":"3519","FudgeFactor":"4901"}},"M":{"REG":{"WeightNum":"166","Height":"3519","FudgeFactor":"4901"},"XR":{"WeightNum":"220","Height":"3519","FudgeFactor":"4901"}}}
,"categoryBasedAppearance":{"F":{},"M":{}},"isRestoreAppearanceFromCookie":false,"heightMappedBMIArray":{"3529":"147","3511":"151","3512":"153","3513":"155","3514":"157","3515":"159","3516":"163","3517":"165","3518":"167","3519":"169","3520":"173","3521":"175","3522":"177","3523":"181","3524":"183","3525":"185","3526":"187","3527":"191","3528":"193"},"MIN_BMI_VALUE":18}
,"ModelAppearanceProperties":{"isEnabled":false,"specialCategoryIDArray":{}}
,"MyContentProperties":{"maxContextPerImage":5
}
,"FitQuestionnaireProperties":{"defaultAnswersMap":{"F":{"BustNum":"","ThighNum":"","HipsNum":"","TorsoNum":"","BraSize":""
,"WaistNum":"","InseamNum":"","HeightNum":"","BirthyearNum":"","CupSize":""},"M":{"NeckNum":"","ThighNum":"","ChestNum":"","WaistbandNum":"","InseamNum":"","SleeveLengthNum":"","HeightNum":"","BirthyearNum":"","SeatNum":""}},"isAutomaticModelUpdate":true}
,"ProfileQuestionnaireProperties":{"retailerNewsletterRegisterUrl":"/server?action=register&email=@Email@","retailerNewsletterUnregisterUrl":"/server?action=unregister&email=@Email@","defaultAnswersMap":{"SigninName":"","HintQuestion":"","Password":"","HintAnswer":"","Email":"","NewsletterRetailer":"false","NewsLetter":"false","PCODE":"","RememberMe":"true","RetypePassword":""},"otherSetAnswersParams":{"AID":"","optinEID":"","optoutEID":""},"isSendEmailForProfileCreatedEnabled":true,"isSendEmailForProfileModifiedEnabled":false}
,"SigninQuestionnaireProperties":{"onForgotPasswordSuccessful":"Anim.openSingle('sectionSaveOptions');Anim.openAndClose('ProfileQuestionnairePanel');"}
,"ECardProperties":{"mailServerSenderAdress":"noreply@mvm.com","defaultAnswersMap":{"senderName":"Product User","senderEmail":"product@mvm.com","recipientEmail1":"mbeauchemin@mvm.com","recipientEmail2":"","recipientEmail3":"","subject":"MVMSE Product ECard","message":"Wow this is  really great!Take a look at me wohoo!!!![$ typeof(ModelQuestionnaire)!='undefined'&&ModelQuestionnaire.getAnswersMap()!=undefined?\"I'm \"+ModelQuestionnaire.getAnswersMap()[\"VMName\"]:'' $]","confirmationMessage":"Your model has been sent to your friend. Thank you. [$ typeof(ModelQuestionnaire)!='undefined'&&ModelQuestionnaire.getAnswersMap()!=undefined?\"I'm \"+ModelQuestionnaire.getAnswersMap()[\"VMName\"]:'' $]"},"pickupLink":""}
,"EMailProperties":{"mailServerSenderAdress":"noreply@mvm.com","defaultParametersMap":{"senderName":"MVM Team","senderEmail":"product@mvm.com","recipientEmail":"","subject":"Welcome to My Virtual Model","message":"New profile created."}}
,"HelpProperties":{"defaultAnswersMap":{"HelpSenderEmail":"","HelpMessage":""}}
,"FitTagProperties":{"isEnabled":true,"isDisplayOnExternalFitDetails":false}
,"FitDetailsProperties":{"isEnabled":true,"isDisplayOnExternalFitDetails":true}
,"StateProperties":{"keyPrefix":{"default":"[$Workspace.retailerCode$].[$Workspace.population$].[$Workspace.skin$].","appearance":"[$Workspace.retailerCode$].[$Workspace.population$]."}}
,"Workspace.messageProperties":{"calloutAttributes":{"templateId":"calloutTemplate","popupImageTopRight":"/images/pop_more_info_top_right.gif","popupImageTopLeft":"/images/pop_more_info_top_left.gif","popupImageBottomLeft":"/images/pop_more_info_bottom_left.gif","popupImageBottomRight":"/images/pop_more_info_bottom_right.gif"},"messageAttributes":{"message": "Default message for messages!","templateId":"messageTemplate","containerSpace":"pageLayout","top":0,"left":0,"width":240,"height":210,"duration":0,"isForcedTopLeft":false,"isClosableOnClick":true,"popupBackground":"/images/pop_standard_message.gif"},"customAttributes":{"modelInfoPopup":{"templateId":"CalloutTemplate"}}}
,"Workspace.sessionProperties":{"isLoggingEnabled":false}
,"FaceMappingProperties":{
"stepControllers":[
"Crop","Tracer","MoveResize"
,"ColorAdjust"
]
,"stepCalls":[
"FaceMapping.stepStart()","FaceMapping.stepCrop()","FaceMapping.stepTracer()","FaceMapping.stepMoveResize()"
,"FaceMapping.stepColorAdjust()","FaceMapping.stepPreview()","FaceMapping.stepPublish()"
]}
,"OverlayProperties":{"stepControllers":[],"stepCalls":[
"Overlay.stepStart()","Overlay.stepPublish()"
]}
,"CameraControlProperties":{}
,"TIMEOUT_URL":"/errors/timeout.html"}
var globalResourceMap=undefined;var environmentConfigMap=undefined;
var Model=undefined;var ModelView=undefined;var ModelAppearance=undefined;var Catalog=undefined;var CatalogFilter=undefined;var CatalogCategory=undefined;var OnMyModel=undefined;var MyHome=undefined;var RoomConfig=undefined;var Favorites=undefined;var ModelQuestionnaire=undefined;var FitQuestionnaire=undefined;var ProfileQuestionnaire=undefined;var SigninQuestionnaire=undefined;var FitTag=undefined;var FitDetails=undefined;var Scene7=undefined;var ItemHistory=undefined;var RemovedItemHistory=undefined;var StorageSolutions=undefined;var ECard=undefined;var EMail=undefined;var Help=undefined;var Tracer=undefined;var MoveResize=undefined;var Crop=undefined;var ColorShift=undefined;var ColorAdjust=undefined;var Media=undefined;var MyContent=undefined;var FaceMapping=undefined;var DragDrop=undefined;var Overlay=undefined;var Tracker=undefined;var CameraControl=undefined;var UnitTest=undefined;
function constructGeometryKey(name,transform){
var key="";var tempValueString="";var nbAfterDot=0;
key+=name;
for(index in transform){
tempValueString=""+(Math.round(transform[index] * 1000))/ 1000.00;
if(tempValueString.indexOf(".")>-1){
nbAfterDot=tempValueString.substring(tempValueString.indexOf(".")).length-1;
if(nbAfterDot>1){tempValueString=tempValueString.substring(0,tempValueString.indexOf(".")+3);}else if(nbAfterDot==1){tempValueString=tempValueString.substring(0,tempValueString.indexOf(".")+2)+"0";}}else{tempValueString+=".00"}
key+="_"+tempValueString;}
return key;}
function constructGeometryName(itemId,colourId,state){
state=state==undefined||state==null?"" : state;
if(state==""){return itemId+"_"+colourId;}
else{return itemId+"_"+colourId+"_"+state;}}
function convertMapToArray(pMap){var newArray=new Array();
for(var anItem in pMap){newArray[newArray.length]=[anItem,decodeURIComponent(pMap[anItem])];}
return newArray;}
function replaceString(pSourceString,pLookupString,pReplaceString){
var splittedString=pSourceString.split(pLookupString);var finalString="";
for(var i=0;i<splittedString.length;i++){
finalString+=splittedString[i];
if(i<splittedString.length-1){finalString+=pReplaceString;}}
return finalString;}
function getLineBreaks(pString){var lineBreaksCount=1;var length=pString.length;for(var i=0;i<length;i++){if(pString.charAt(i)=="\r"){lineBreaksCount++;}}
return lineBreaksCount;}
function getPatchedUrl(url,prefix,suffix){
var finalUrl="";
if(url.indexOf(".gif")>-1){finalUrl=prefix+url.split(".gif")[0]+suffix+".gif";}else if(url.indexOf(".jpg")>-1){finalUrl=prefix+url.split(".jpg")[0]+suffix+".jpg";}else if(url.indexOf(".png")>-1){finalUrl=prefix+url.split(".png")[0]+suffix+".png";}else{finalUrl=prefix+url+suffix;}
return finalUrl;}
function getQuery(){
var url=location.href.split("#")[0];var tmpArray=new Array();var query=new Object();
if(url.indexOf("?")>0){tmpArray=url.split("?")[1].split("&");
for(var i=0;i<tmpArray.length;i++){eval("query."+tmpArray[i].split("=")[0]+"=tmpArray[i].split('=')[1]");}}
return query;}
function formatColorCode(pColorCode){var colorLength=pColorCode.length;var prefix="";
for(i=colorLength;i<6;i++){prefix+="0";}
return prefix+pColorCode;}
function formatFloat(number,places){var shift=1;var j;for(j=0;j<places;j++)
shift=(shift * 10);number=Math.round(number * shift);number=number/shift;return number;}
function setNumberDecimals(number,nbDecimals,decimalSign){
if(isNaN(number)){number=0;}
nbDecimals=nbDecimals||2;decimalSign=decimalSign||".";var strNumber=""+number;
var decimalIndex=strNumber.indexOf(decimalSign);
if(decimalIndex==-1){strNumber+=decimalSign;for(i=0,j=nbDecimals;i<j;i++){strNumber+="0";}
return strNumber;}
var currentDecimalsNb=strNumber.length-(decimalIndex+1);
if(currentDecimalsNb==nbDecimals){return strNumber;}
if(currentDecimalsNb<nbDecimals){for(i=currentDecimalsNb,j=nbDecimals;i<j;i++){strNumber+="0";}
return strNumber;}
var extraDecimals=currentDecimalsNb-nbDecimals;return strNumber.substring(0,(strNumber.length-extraDecimals));}
function meas_type(strInput){var measType1=/(^[ ]*\d+(([ ]+\d+(\.\d+)?\/\d+(\.\d+)?)|(\.\d+([ ]+\d+(\.\d+)?\/\d+(\.\d+)?)?))?[ ]*$)/;var measType2=/(^[ ]*\d+\/\d+[ ]*$)/;var measType3=/(^[ ]*\.\d+([ ]+\d+(\.\d+)?\/\d+(\.\d+)?)?)[ ]*$/;var measType4=/(^[ ]*$)/;var measType5=/(^[ ]*\d+(\.\d+)?[ ]*['][ ]*((\d+(([ ]+\d+(\.\d+)?\/\d+(\.\d+)?)|(\.\d+([ ]+\d+(\.\d+)?\/\d+(\.\d+)?)?))?)|(\.\d+([ ]+\d+(\.\d+)?\/\d+(\.\d+)?)?)|((\d+(\.\d+)?\/\d+(\.\d+)?)?))[ ]*$)/;
if(measType1.test(strInput))
return(1);else if(measType2.test(strInput))
return(1);else if(measType3.test(strInput))
return(1);else if(measType4.test(strInput))
return(1);else if(measType5.test(strInput))
return(2);else
return(-1);}
function fractToStr(fractStr){var parseArray
parseArray=fractStr.split("/");
if(parseFloat(parseArray[1])!=0)
return(parseFloat(parseArray[0])/parseFloat(parseArray[1]));else{return(-1);}}
function convertFractToDecimal(strInput){
var parseStr;var parseArray;var fractVal;var returnVal;var i;
switch(meas_type(strInput)){case 1:
parseStr=new String(trim(strInput));parseArray=parseStr.split(/[ ]+/);
for(i=0;i<parseArray.length;i++){parseArray[i]=trim(parseArray[i]);}
if(parseArray.length==1){if(parseArray[0]!=""){var fractParse;fractParse=parseArray[0].split("/");if(fractParse.length==1){return formatFloat(parseFloat(parseArray[0]),3);}else{fractVal=fractToStr(parseArray[0]);if(fractVal!=-1){return formatFloat(fractVal,3);}else{return(NaN);}}}else{return "";}}
else{fractVal=fractToStr(parseArray[1]);if(fractVal!=-1){return formatFloat((parseFloat(parseArray[0])+fractVal),3);}else{return(NaN);}}
break;case 2:
var feetStr;var parseArray2
parseStr=new String(trim(strInput));parseArray=parseStr.split("'");
for(i=0;i<parseArray.length;i++){parseArray[i]=trim(parseArray[i]);}
feetStr=parseFloat(parseArray[0])* 12;parseArray2=parseArray[1].split(/[ ]+/);
for(i=0;i<parseArray2.length;i++){parseArray2[i]=trim(parseArray2[i]);}
if(parseArray2.length==1){var fractParse;fractParse=parseArray2[0].split("/");if(fractParse.length==1){returnVal=formatFloat((feetStr+parseFloat(parseArray2[0])),3);return returnVal;}else{fractVal=fractToStr(parseArray2[0]);if(fractVal!=-1){return formatFloat((feetStr+fractVal),3);}else{return(NaN);}}}
else{fractVal=fractToStr(parseArray2[1]);if(fractVal!=-1){returnVal=formatFloat((feetStr+parseFloat(parseArray2[0])+fractVal),3);return returnVal;}else{return(NaN);}}
break;case-1:
return(NaN);break;}
return(NaN);}
function encodeToUnicode(pText){
var pText=escape(pText);var finaldata="";var i=0;
while(i<pText.length){if(pText.substring(i,i+2)=="%u"){finaldata+="&#"+parseInt(pText.substring(i+2,i+6),16)+";";i=i+5;}else if(pText.substring(i,i+6)=="%0D%0A"){finaldata+="<br>";i=i+5;}else if(pText.substring(i,i+1)=="%"){finaldata+=unescape(pText.substring(i,i+3));i=i+2;}else{finaldata+=pText.charAt(i);}
i=i+1;}
return finaldata;}
function isEmail(myEmail){
return myEmail.match(/^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/)!=undefined;}
function trim(strText){
strText=strText+"";
while(strText.substring(0,1)==' ')
strText=strText.substring(1,strText.length);
while(strText.substring(strText.length-1,strText.length)==' ')
strText=strText.substring(0,strText.length-1);
return strText;}
function defaultIfEmpty(value,defaultValue){
if(value==undefined||value==null||value==""){value=defaultValue;}
return value;}
function CookieController(id){
this.id=id;this.checkCookieSupport();this.updateCookies();}
CookieController.prototype.id="CookieController";CookieController.prototype.data=new Array();CookieController.prototype.domain=".mvm.com"
CookieController.prototype.cookie="";CookieController.prototype.thread=undefined;CookieController.prototype.isCookieSupported=false;CookieController.prototype.isPermanentCookieSupported=false;CookieController.prototype.isSessionCookieSupported=false;CookieController.prototype.checkTime=1000;
CookieController.prototype.loadCookies=function(){
var cookieData="";var iCount=0;
this.cookie=document.cookie+"";this.data=new Array();var cookies=this.cookie.split(";");var cookie=undefined;
for(var cookieIndex in cookies){cookie=cookies[cookieIndex].split("=");
this.data[trim(cookie[0])]=(this.data[trim(cookie[0])]!=undefined?this.data[trim(cookie[0])]+";" : "")+decodeURIComponent(cookie.slice(1,cookie.length).join("="));}}
CookieController.prototype.updateCookies=function(){
if(this.cookie!=document.cookie+""&&typeof(Workspace)!="undefined" &&typeof(Workspace.events)!="undefined"){
this.loadCookies();Workspace.events.throwEvent(Workspace.events.EVENT_COOKIE_CHANGED,this);}
this.thread=setTimeout(this.id+".updateCookies()",this.checkTime);}
CookieController.prototype.checkCookieSupport=function(){
var isPermanentCookieSupported=false;var isSessionCookieSupported=false;
this.setAttribute("_cookieTestPermanent","test");this.setAttribute("_cookieTestSession","test",true);
this.isPermanentCookieSupported=(document.cookie.indexOf("_cookieTestPermanent")>-1?true : false);this.isSessionCookieSupported=(document.cookie.indexOf("_cookieTestSession")>-1?true : false);
this.deleteCookie("_cookieTestPermanent");this.deleteCookie("_cookieTestSession");
this.isCookieSupported=(this.isPermanentCookieSupported&&this.isPermanentCookieSupported?true : false);}
CookieController.prototype.refresh=function(){
this.updateCookies();}
CookieController.prototype.writeCookie=function(key,value,expires,domain){
domain=(domain!=undefined?domain : this.domain);
if(key!="rememberMe"&&key!="rememberMeCookie"){value=encodeURIComponent(value);}
this.deleteCookie(key);
document.cookie=
key+"="+
value+";"+
"path=/;"+(domain!=""?"domain="+domain+";" : "")+(expires==undefined?"expires="+new Date(2050,01,01).toGMTString(): expires);
this.loadCookies();}
CookieController.prototype.setAttribute=function(key,value,isForSessionOnly){
this.data[key]=value;this.writeCookie(key,value,(isForSessionOnly!=undefined&&isForSessionOnly==true?"" : undefined));}
CookieController.prototype.deleteCookie=function(key){
document.cookie=key+"=;expires="+new Date(1900,01,01).toGMTString()+";domain="+this.domain+";path=/";this.loadCookies();}
CookieController.prototype.getAttribute=function(key){
return this.data[key];}
var CookieUtils=new CookieController("CookieUtils");
function DataExchangeTunnel(pId){
this.id=pId;
this.activeConnectionArray=new Array();this.groupConnectionMap=new Array();this.timeoutTrackerMap=new Array();this.standbyConnectionList=new Array();}
DataExchangeTunnel.prototype.id="DataExchangeTunnel";DataExchangeTunnel.prototype.isInitialized=false;DataExchangeTunnel.prototype.activeConnectionArray=undefined;DataExchangeTunnel.prototype.groupConnectionMap=undefined;DataExchangeTunnel.prototype.connectionSerialCount=0;DataExchangeTunnel.prototype.serverURL="/";DataExchangeTunnel.prototype.isDebugActive=true;DataExchangeTunnel.prototype.debugResponse=false;DataExchangeTunnel.prototype.timeoutTrackerMap=undefined;DataExchangeTunnel.prototype.defaultConnectionGroup="generic";DataExchangeTunnel.prototype.isSynchronized=false;
DataExchangeTunnel.prototype.STATUS_CREATED="|created";DataExchangeTunnel.prototype.STATUS_OPENED="|opened";DataExchangeTunnel.prototype.STATUS_WAITING="|waiting";DataExchangeTunnel.prototype.STATUS_VALID_RESPONSE="|valid response";DataExchangeTunnel.prototype.STATUS_INVALID_RESPONSE="|INVALID response";DataExchangeTunnel.prototype.STATUS_ERROR="|error";DataExchangeTunnel.prototype.STATUS_CLOSED="|closed";DataExchangeTunnel.prototype.STATUS_TIMEOUT="|timeout";
DataExchangeTunnel.prototype.RESPONSE_FORMAT_ARRAY=0;DataExchangeTunnel.prototype.RESPONSE_FORMAT_XML=1;DataExchangeTunnel.prototype.RESPONSE_FORMAT_TEXT=2;
DataExchangeTunnel.prototype.ERROR_INVALID_RESPONSE="invalidResponse";DataExchangeTunnel.prototype.ERROR_TIMEOUT="timeout";
DataExchangeTunnel.prototype.init=function(){
this.isInitialized=true;}
DataExchangeTunnel.prototype.onStateChange=function(){
var connection=undefined;var estimatedActiveConnectionCount=0;
for(var index in det.activeConnectionArray){
connection=det.activeConnectionArray[index];if(connection!=undefined&&connection.active==true){
if(connection.httpRequest.readyState==4){connection.active=false;det.processResponse(connection);
if(connection.group!=undefined){det.processGroupedConnection(connection);}
}else{estimatedActiveConnectionCount++;}}}
if(estimatedActiveConnectionCount==0){
if(det.activeConnectionArray.length>10){det.activeConnectionArray=det.activeConnectionArray.slice(det.activeConnectionArray.length-10,det.activeConnectionArray.length);}
Workspace.events.throwEvent(Workspace.events.EVENT_SERVER_ALL_REQUESTS_COMPLETED,this);}}
DataExchangeTunnel.prototype.processResponse=function(connection){
var responseMap=new Array();var responseText=connection.httpRequest.responseText;
connection.timeReceived=new Date();
if(connection.timeoutThread!=undefined){clearTimeout(connection.timeoutThread);}
if(this.isDebugActive&&typeof(log)!="undefined"){log.debug("(RESPONSE)"+connection.id+"("+(connection.timeReceived.getTime()-connection.timeSent.getTime())/1000+"s "+" "+(Math.floor(responseText.length/1024*100))/100+"KB)-"+connection.serverUrl+(this.debugResponse?"\n\r\t"+(responseText.length>1000?responseText.substring(0,1000)+"..." : responseText): ""),this);}
if(connection.responseFormat==this.RESPONSE_FORMAT_TEXT){
connection.status+=this.STATUS_VALID_RESPONSE;responseMap["textResponse"]=responseText;
}else if(connection.httpRequest.status==200){
if(connection.responseFormat==this.RESPONSE_FORMAT_ARRAY){
if(responseText.indexOf("[")==0){responseMap=eval(responseText)[0];
}else if(responseText.length==0){responseMap=new Array();
}else{connection.status+=this.STATUS_INVALID_RESPONSE;responseMap=undefined;}
}else if(connection.responseFormat==this.RESPONSE_FORMAT_XML){
if(connection.httpRequest.responseXML!=undefined){connection.status+=this.STATUS_VALID_RESPONSE;responseMap=xmlParser.convertXmlToMap(connection.httpRequest.responseXML.documentElement);}else{connection.status+=this.STATUS_INVALID_RESPONSE;responseMap=undefined;}}
}else{connection.status+=this.STATUS_INVALID_RESPONSE;responseMap=undefined;connection.error=this.ERROR_INVALID_RESPONSE;}
if(responseMap==undefined||(responseMap["errorCode"]!=undefined&&responseMap["errorCode"]==Workspace.ERROR_SESSION_TIMEOUT)){
connection.status+=this.STATUS_INVALID_RESPONSE;
if(typeof(Workspace)!="undefined"){if(responseMap!=undefined&&responseMap["errorCode"]==Workspace.ERROR_SESSION_TIMEOUT){
this.standbyConnectionList.push(connection);Workspace.recoverServerSession();}else{
Workspace.events.throwEvent(
Workspace.events.EVENT_SERVER_INVALID_REQUEST,
connection);
log.error("Invalid response: [id:"+connection.id+" action:"+connection.action+" content:"+connection.responseText+"]",this);}}
responseMap=undefined;
}else{
connection.response=responseMap;
if(connection.onCompleteScript!=undefined){eval(connection.onCompleteScript);}
Workspace.events.throwEvent(
Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,connection);}
connection.httpRequest=null;
connection.status+=this.STATUS_CLOSED;}
DataExchangeTunnel.prototype.sendRequest=function(attributes){
if(!this.isInitialized){this.init();}
var newConnection=this.createConnection(attributes);
this.activeConnectionArray[this.activeConnectionArray.length]=newConnection;
if(newConnection.group==undefined){this._send(newConnection);}else{this.addGroupedConnection(newConnection);}}
DataExchangeTunnel.prototype.addGroupedConnection=function(connection){
var groupId=connection.group;
this.groupConnectionMap[groupId]=(this.groupConnectionMap[groupId]!=undefined?this.groupConnectionMap[groupId] : new Array());
this.groupConnectionMap[groupId].push(connection);
if(this.groupConnectionMap[groupId].length==1){this._send(connection);}}
DataExchangeTunnel.prototype.processGroupedConnection=function(connection){
var groupId=connection.group;
if(this.groupConnectionMap[groupId][0]==connection){this.groupConnectionMap[groupId].shift();}
if(this.groupConnectionMap[groupId]!=undefined&&this.groupConnectionMap[groupId].length>0){this._send(this.groupConnectionMap[groupId][0]);}}
DataExchangeTunnel.prototype._send=function(connection){
var todayDate=new Date();
connection.httpRequest.onreadystatechange=this.onStateChange;
if(this.isDebugActive&&typeof(log)!="undefined"){var callingControllerId=(connection.callingController!=undefined&&connection.callingController.id!=undefined?connection.callingController.id : "");log.debug("(REQUEST)"+connection.id+"-["+callingControllerId+"] "+connection.serverUrl+"?"+connection.query,this);}
Workspace.events.throwEvent(
Workspace.events.EVENT_SERVER_REQUEST_SENT,connection);
if(connection.timeout!=undefined){connection.timeoutThread=setTimeout(this.id+".handleConnectionTimeout('"+connection.id+"')",connection.timeout);}
if(connection.method=="POST"){
connection.timeSent=new Date();
connection.httpRequest.open(
"POST",connection.serverUrl+(connection.action!=undefined?"?actionType="+connection.action : ""),!connection.isSynchronized);
connection.query=(connection.query==undefined?"" : connection.query);
connection.httpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");connection.httpRequest.setRequestHeader("Content-Length",connection.query.length);connection.httpRequest.setRequestHeader("If-Modified-Since",new Date(todayDate.getYear(),todayDate.getMonth(),todayDate.getDate()+1).toString());
connection.httpRequest.send(connection.query);}else{
connection.timeSent=new Date();
connection.httpRequest.open(
"GET",connection.serverUrl+(connection.query!=""?(connection.query.indexOf("?")!=0?"?" : "")+connection.query : ""),!connection.isSynchronized);
connection.httpRequest.setRequestHeader("If-Modified-Since",new Date(todayDate.getYear(),todayDate.getMonth(),todayDate.getDate()+1).toString());
connection.httpRequest.send(null);}
connection.status+=det.STATUS_OPENED;}
DataExchangeTunnel.prototype.handleConnectionTimeout=function(connectionId){
var index=0;while(det.activeConnectionArray[index].id!=connectionId){index++;}
var connection=det.activeConnectionArray[index]
if(connection.id==connectionId){
connection.status+=this.STATUS_TIMEOUT;connection.httpRequest.abort();connection.httpRequest=null;connection.error=this.ERROR_TIMEOUT;
if(connection.onCompleteScript!=undefined){eval(connection.onCompleteScript);}
log.error("Connection timeout: "+connection.serverUrl,this);
Workspace.events.throwEvent(
Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,connection);}}
DataExchangeTunnel.prototype.getHTTPObject=function(){
var xmlhttp;
/*@cc_on
@if(@_jscript_version>=5)
try{xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");}
catch(e){try{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
catch(E){xmlhttp=false;}}
@else
xmlhttp=false;@end @*/
if(!xmlhttp&&typeof XMLHttpRequest!='undefined'){try{xmlhttp=new XMLHttpRequest();}
catch(e){log.error("AJAX Not supported on this browser/OS");xmlhttp=false;}}
return xmlhttp;}
DataExchangeTunnel.prototype.createConnection=function(attributes){
var newConnection=new Object();
var requestParams="";var parametersMap=new Array();
if(attributes["parameters"]!=undefined&&attributes["parameters"][0]!=undefined){
for(var i=0;i<attributes["parameters"].length;i++){requestParams+=(requestParams==""?"":"&")+attributes["parameters"][i][0]+"="+attributes["parameters"][i][1];parametersMap[attributes["parameters"][i][0]]=attributes["parameters"][i][1];}
}else if(attributes["parameters"]!=undefined&&attributes["parameters"]!=""){requestParams=attributes["parameters"];}
newConnection.action=(attributes["action"]!=undefined?attributes["action"] : "");newConnection.timeSent=undefined;newConnection.timeReceived=undefined;newConnection.serverUrl=(attributes["serverUrl"]!=undefined?attributes["serverUrl"] : this.serverURL);newConnection.active=true;newConnection.httpRequest=this.getHTTPObject();newConnection.id="connection"+(this.connectionSerialCount++);newConnection.query=(attributes["query"]!=undefined?attributes["query"] : requestParams);newConnection.method=(attributes["method"]!=undefined?attributes["method"] : "POST");newConnection.status=this.STATUS_CREATED;newConnection.callingController=(attributes["callingController"]!=undefined?attributes["callingController"] : undefined);newConnection.responseFormat=(attributes["responseFormat"]!=undefined?attributes["responseFormat"] : this.RESPONSE_FORMAT_ARRAY);newConnection.response=new Array();newConnection.parametersMap=(attributes["parametersMap"]!=undefined?attributes["parametersMap"] : parametersMap);newConnection.onCompleteScript=(attributes["onCompleteScript"]!=undefined?attributes["onCompleteScript"] : undefined);newConnection.info=(attributes["info"]!=undefined?attributes["info"] : undefined);newConnection.group=(attributes["group"]!=undefined?attributes["group"] : this.defaultConnectionGroup);newConnection.isSynchronized=(attributes["isSynchronized"]!=undefined?attributes["isSynchronized"] : this.isSynchronized);newConnection.timeout=(attributes["timeout"]!=undefined?attributes["timeout"] : undefined);newConnection.timeoutThread=undefined;newConnection.error=undefined;
return newConnection;}
DataExchangeTunnel.prototype.catchEvent=function(eventKey,attributes){
}
var det=new DataExchangeTunnel("det");
function EventController(){}
EventController.prototype.EVENT_SERVER_RESPONSE_RECEIVED="EVENT_SERVER_RESPONSE_RECEIVED";EventController.prototype.EVENT_SERVER_REQUEST_SENT="EVENT_SERVER_REQUEST_SENT";EventController.prototype.EVENT_SERVER_ALL_REQUESTS_COMPLETED="EVENT_SERVER_ALL_REQUESTS_COMPLETED";EventController.prototype.EVENT_SERVER_INVALID_REQUEST="EVENT_SERVER_INVALID_REQUEST";
EventController.prototype.EVENT_INITIALIZED="EVENT_INITIALIZED";EventController.prototype.EVENT_INIT_FAILURE="EVENT_INIT_FAILURE";EventController.prototype.EVENT_SKIN_LOADED="EVENT_SKIN_LOADED";EventController.prototype.EVENT_PAGE_LOADED="EVENT_PAGE_LOADED";EventController.prototype.EVENT_CONTROLLER_INITIALIZED="EVENT_CONTROLLER_INITIALIZED";EventController.prototype.EVENT_RESOURCES_LOADED="EVENT_RESOURCES_LOADED";
EventController.prototype.EVENT_COOKIE_CHANGED="EVENT_COOKIE_CHANGED";EventController.prototype.EVENT_IFRAME_EXPAND="EVENT_IFRAME_EXPAND";EventController.prototype.EVENT_IFRAME_COLLAPSE="EVENT_IFRAME_COLLAPSE";EventController.prototype.EVENT_PRODUCT_PAGE_CALL="EVENT_PRODUCT_PAGE_CALL";EventController.prototype.EVENT_BUYOUTFIT_PAGE_CALL="EVENT_BUYOUTFIT_PAGE_CALL";
EventController.prototype.EVENT_USER_STATE_CHANGE="EVENT_USER_STATE_CHANGE";EventController.prototype.EVENT_USER_SIGNIN="EVENT_USER_SIGNIN";EventController.prototype.EVENT_USER_SIGNOUT="EVENT_USER_SIGNOUT";EventController.prototype.EVENT_USER_AUTHENTICATED="EVENT_USER_AUTHENTICATED";EventController.prototype.EVENT_PROFILE_CREATED="EVENT_PROFILE_CREATED";EventController.prototype.EVENT_PROFILE_MODIFIED="EVENT_PROFILE_MODIFIED";EventController.prototype.EVENT_PROFILE_UPDATED="EVENT_PROFILE_UPDATED";EventController.prototype.EVENT_PROFILE_DELETED="EVENT_PROFILE_DELETED";
EventController.prototype.EVENT_MODEL_ATTRIBUTES_CHANGED="EVENT_MODEL_ATTRIBUTES_CHANGED";EventController.prototype.EVENT_MODEL_INITIALIZED="EVENT_MODEL_INITIALIZED";EventController.prototype.EVENT_MODEL_RESET="EVENT_MODEL_RESET";EventController.prototype.EVENT_MODEL_CLEARED="EVENT_MODEL_CLEARED";EventController.prototype.EVENT_MODEL_IMAGE_CHANGED="EVENT_MODEL_IMAGE_CHANGED";EventController.prototype.EVENT_MODEL_IMAGE_LOADING="EVENT_MODEL_IMAGE_LOADING";EventController.prototype.EVENT_MODEL_ONMOUSEOVER="EVENT_MODEL_ONMOUSEOVER";EventController.prototype.EVENT_MODEL_ONMOUSECLICK="EVENT_MODEL_ONMOUSECLICK";EventController.prototype.EVENT_MODEL_ONMOUSEDOWN="EVENT_MODEL_ONMOUSEDOWN";EventController.prototype.EVENT_MODEL_LAYOUT_CHANGED="EVENT_MODEL_LAYOUT_CHANGED";EventController.prototype.EVENT_MODEL_CONTENT_CHANGED="EVENT_MODEL_CONTENT_CHANGED";EventController.prototype.EVENT_BODYSET_CHANGED="EVENT_BODYSET_CHANGED";EventController.prototype.EVENT_MODEL_ITEM_TRYON="EVENT_MODEL_ITEM_TRYON";EventController.prototype.EVENT_MODEL_ITEM_REMOVE="EVENT_MODEL_ITEM_REMOVE";EventController.prototype.EVENT_MODEL_ITEM_MOUSEOVER="EVENT_MODEL_ITEM_MOUSEOVER";EventController.prototype.EVENT_MODEL_ITEM_MOUSEDOWN="EVENT_MODEL_ITEM_MOUSEDOWN";EventController.prototype.EVENT_MODEL_ITEM_MOUSEOUT="EVENT_MODEL_ITEM_MOUSEOUT";EventController.prototype.EVENT_INSTANCE_SELECTION_START="EVENT_INSTANCE_SELECTION_START";EventController.prototype.EVENT_INSTANCE_SELECTION_STOPPED="EVENT_INSTANCE_SELECTION_STOPPED";EventController.prototype.EVENT_CAMERA_CHANGED="EVENT_CAMERA_CHANGED";EventController.prototype.EVENT_INCOMPATIBLE_ITEM_REMOVED="EVENT_INCOMPATIBLE_ITEM_REMOVED";EventController.prototype.EVENT_INCOMPATIBLE_ITEM_TRYON="EVENT_INCOMPATIBLE_ITEM_TRYON";EventController.prototype.EVENT_ALTERNATE_ITEM_TRYON="EVENT_ALTERNATE_ITEM_TRYON";EventController.prototype.EVENT_INCOMPATIBLE_ITEM_ALTERNATE="EVENT_INCOMPATIBLE_ITEM_ALTERNATE";EventController.prototype.EVENT_WEIGHTLOSS_INCOMPATIBLE_ITEM_REMOVED="EVENT_WEIGHTLOSS_INCOMPATIBLE_ITEM_REMOVED";EventController.prototype.EVENT_BMI_REAJUSTED="EVENT_BMI_REAJUSTED";
EventController.prototype.EVENT_ONMYMODEL_ITEM_SELECTED="EVENT_ONMYMODEL_ITEM_SELECTED";EventController.prototype.EVENT_ONMYMODEL_CHANGED="EVENT_ONMYMODEL_CHANGED";
EventController.prototype.EVENT_MODEL_MAP_LOADED="EVENT_MODEL_MAP_LOADED";
EventController.prototype.EVENT_CATALOG_CATEGORY_CHANGED="EVENT_CATALOG_CATEGORY_CHANGED";EventController.prototype.EVENT_CATEGORY_TREE_UPDATED="EVENT_CATEGORY_TREE_UPDATED";
EventController.prototype.EVENT_UPLOAD_STARTED="EVENT_UPLOAD_STARTED";EventController.prototype.EVENT_UPLOAD_COMPLETED="EVENT_UPLOAD_COMPLETED";EventController.prototype.EVENT_FACEMAPPING_START="EVENT_FACEMAPPING_START";EventController.prototype.EVENT_FACEMAPPING_END="EVENT_FACEMAPPING_END";EventController.prototype.EVENT_CONTENT_CREATED="EVENT_CONTENT_CREATED";EventController.prototype.EVENT_CONTENT_DELETED="EVENT_CONTENT_DELETED";
EventController.prototype.EVENT_FAVORITES_ADDED="EVENT_FAVORITES_ADDED";EventController.prototype.EVENT_FAVORITES_REMOVED="EVENT_FAVORITES_REMOVED";
EventController.prototype.EVENT_FIT_CREATED="EVENT_FIT_CREATED";EventController.prototype.EVENT_FIT_ATTRIBUTES_CHANGED="EVENT_FIT_ATTRIBUTES_CHANGED";
EventController.prototype.EVENT_REMOVED_HISTORY_ADDED="EVENT_REMOVED_HISTORY_ADDED";
EventController.prototype.EVENT_ECARD_SENT="EVENT_ECARD_SENT";
EventController.prototype.EVENT_EMAIL_SENT="EVENT_EMAIL_SENT";
EventController.prototype.EVENT_WINDOW_GENERATE="EVENT_WINDOW_GENERATE";EventController.prototype.EVENT_WINDOW_SHOW="EVENT_WINDOW_SHOW";EventController.prototype.EVENT_WINDOW_HIDE="EVENT_WINDOW_HIDE";
EventController.prototype.id="EventController";EventController.prototype.eventListenersMap=new Array();EventController.prototype.eventScriptMap=new Array();EventController.prototype.isLogging=true;
EventController.prototype.throwEvent=function(eventKey,attributes){
if(this.isLogging){log.debug("Event "+eventKey+" thrown",this);}
var listenersArray=this.eventListenersMap[eventKey];var scriptsArray=this.eventScriptMap[eventKey];
if(listenersArray!=undefined){
for(var controllerId in listenersArray){if(listenersArray[controllerId]!=undefined){listenersArray[controllerId].catchEvent(eventKey,attributes);}}}
if(scriptsArray!=undefined){
for(var index in scriptsArray){if(scriptsArray[index]!=undefined){eval(scriptsArray[index]["jsCode"]);if(scriptsArray[index]["isOneTimeOnly"]){scriptsArray[index]=undefined;}}}}
if(typeof(catchAllEvent)!="undefined"){catchAllEvent(eventKey,attributes);}}
EventController.prototype.addListener=function(eventKey,controllerObject){
if(eventKey!=undefined&&eventKey!=""&&controllerObject!=undefined){
if(this.eventListenersMap[eventKey]==undefined){this.eventListenersMap[eventKey]=new Array();}
this.eventListenersMap[eventKey][controllerObject.id]=controllerObject;}
return this.eventListenersMap[eventKey].length-1;}
EventController.prototype.isEventListener=function(eventKey,controllerObject){
return this.eventListenersMap[eventKey][controllerObject.id]!=undefined?true : false;}
EventController.prototype.addEventScript=function(eventKey,jsCode,isOneTimeOnly){
if(eventKey!=undefined&&eventKey!=""&&jsCode!=undefined&&jsCode!=""){var scriptsArray=(this.eventScriptMap[eventKey]!=undefined?this.eventScriptMap[eventKey] : new Array());
var isUnique=true;
for(var index in scriptsArray){if(scriptsArray[index]!=undefined&&jsCode==scriptsArray[index]["jsCode"]){isUnique=false;break;}}
if(isUnique){scriptsArray[scriptsArray.length]={"jsCode":jsCode,"isOneTimeOnly":(isOneTimeOnly==undefined?false : isOneTimeOnly)}
this.eventScriptMap[eventKey]=scriptsArray;}}
return this.eventScriptMap[eventKey].length-1;}
function IFramePost(pId){this.id=pId;}
IFramePost.prototype.id="IFramePost";IFramePost.prototype.lastIFrameContent="";IFramePost.prototype.communicationFrameId="iFramePost";IFramePost.prototype.sendRequest=function(url,params,method){method=method!=undefined?method : "POST";var communicationFrame=getE(this.communicationFrameId);var form=document.createElement("FORM");var field=undefined;form.method=method;form.action=url;form.target=this.communicationFrameId;for(var key in params){field=document.createElement("INPUT");field.type="hidden";field.name=key;field.value=params[key];form.appendChild(field);}document.body.appendChild(form);form.submit();}
var ifPost=new IFramePost("ifPost");
function JSClass(){}
JSClass.prototype.extend=function(object,superClassArray){
var superClass=undefined;
if(superClassArray[0]!=undefined){
for(var i=0;i<superClassArray.length;i++){
superClass=superClassArray[i];
if(superClass!=undefined&&superClass.prototype!=undefined){
for(var attribute in superClass.prototype){
if(eval("object."+attribute+"==undefined")&&attribute!="id"){eval("object."+attribute+"=superClass.prototype."+attribute);}
if(superClass.prototype.id==undefined||superClass.prototype.id==""){log.error("superClass ID is not defined or empty for object ["+object.id+"]");}
eval("object.super_"+superClass.prototype.id+"_"+attribute+"=superClass.prototype."+attribute);}}else{log.error("extend(): Class undefined("+superClass.toString()+")");}}}else{log.error("extend(): Expected parameter superClassArray{Array}");}}
JSClass.prototype.cast=function(object, castClass){
for(var attribute in superClass.prototype){
if(eval("object."+attribute+"==undefined")){eval("object."+attribute+"=superClass.prototype."+attribute);}}}
JSClass.prototype.implementsLoggeable=function(object){
if(getQuery().log=="debug"){
var logCodeLine="";var functionCodeArray=new Array();
for(var attribute in object){
logCodeLine="log.debug(\" ~ \"+this.id+\"."+attribute+"(\"+jsClass.getArgumentList(arguments)+\")\");";
if(typeof(object[attribute])=="function"){
functionCodeArray=object[attribute].toString().split("{");functionCodeArray[1]=logCodeLine+functionCodeArray[1];
eval("object[attribute]="+functionCodeArray.join("{"));}}}}
JSClass.prototype.implementsProfiling=function(object){
var functionCode="";
if(getQuery().log=="debug"){
for(var attribute in object){
if(typeof(object[attribute])=="function"){
functionCode=object[attribute].toString();functionCode=functionCode.replace(/(.*)\{(.*)/,"$1{\nProfiler.methodIn(this.id+'."+attribute+"');\n$2");functionCode=functionCode.substring(0,functionCode.length-1)+"Profiler.methodOut(this.id+'."+attribute+"');"+"}";
eval("object[attribute]="+functionCode);log.debug("Attached profiler to "+(object.id!=undefined?object.id : "[Object]")+"."+attribute);}}}}
JSClass.prototype.getArgumentList=function(methodArguments){
var argumentsString="";
for(var i=0;i<methodArguments.length;i++){
if(methodArguments[i]!=""){if(typeof(methodArguments[i])=="object"&&methodArguments[i].id!=undefined&&methodArguments[i].id!=""){argument="("+typeof(methodArguments[i])+")"+methodArguments[i].id}else{try{argument=MapUtils.toJSON(methodArguments[i]);if(argument.length>100){argument=argument.substring(0,100)+"...";}}catch(e){argument="[Parse error] Cause : "+e.message;}}
argumentsString+=argument;
if(i<methodArguments.length-1){argumentsString+=","}}}
return argumentsString}
var jsClass=new JSClass();
function Map(array){
this.array=(array!=undefined?array : new Array());}
Map.prototype.array=undefined;
Map.prototype.get=function(key,map){
if(key!=undefined){return this.getMapValue(key,(map!=undefined?map : this.array));}else{log.error("get()called with undefined key",this);}}
Map.prototype.getIndex=function(index,map){
map=(map!=undefined?map : this.array)
var iCount=0;var returnValue=undefined;
for(var key in map){
if(iCount==index){returnValue=map[key];break;}
iCount++;}
return returnValue;}
Map.prototype.getKeyAtIndex=function(index,map){
map=(map!=undefined?map : this.array)
var iCount=0;var returnValue=undefined;
for(var key in map){
if(iCount==index){returnValue=key;break;}
iCount++;}
return returnValue;}
Map.prototype.getCount=function(map){
var iCount=0;
for(var key in map){iCount++;}
return iCount;}
Map.prototype.put=function(key,value,map){
this.array=this.setMapValue(key,value,(map!=undefined?map : this.array));}
Map.prototype.getMapValue=function(multiLevelKey,map){
map=(map!=undefined?map : this.array);
if(map[multiLevelKey]!=undefined){return map[multiLevelKey];}else{try{return eval("map[\""+multiLevelKey.replace(new RegExp("\/","g"),"\"][\"")+"\"]");}catch(e){return undefined;}}}
/**
* Sets the value of a key within a multi-level object
* @param{multiLevelKey}multiLevelKeySlash-seperated key chain
* @param{Object}valueObject to set as value
* @param{Map/Array}mapMap/Array embedded objects structure
* @param{String}separator(optional)Separator
* @type Map/Array
* @return Modified Map/Array
*/
Map.prototype.setMapValue=function(multiLevelKey,value,map,separator){
separator=(separator!=undefined?separator : "/");
var isSet=false;var keyArray=multiLevelKey.split("/");
for(var key in map){
if(isSet){break;}
if(keyArray[0]==key){
if(keyArray.length>1){
map[key]=this.setMapValue(
keyArray.slice(1,keyArray.length).join("/"),value,map[key],separator);}else{map[key]=value;isSet=true;}}}
return map;}
Map.prototype.removeDuplicatesFromArray=function(array){
var tmpMap=new Array();var finalArray=new Array();
if(array!=undefined&&array.length!=undefined){
for(i=0;i<array.length;i++){tmpMap[array[i]]=array[i];}
for(index in tmpMap){finalArray[finalArray.length]=tmpMap[index];}}
return finalArray;}
Map.prototype.removeIndexFromArray=function(index,array){
var newArray=new Array();
for(var i in array){if(i!=index){newArray[newArray.length]=array[i];}}
return newArray;}
Map.prototype.toString=function(map,keyValueSeparator,pairSeparator){
map=(map==undefined?this.array : map);keyValueSeparator=(keyValueSeparator!=undefined?keyValueSeparator : ":");pairSeparator=(pairSeparator!=undefined?pairSeparator : ",");
var serializedString="";
for(var key in map){
if(serializedString!=""){serializedString+=pairSeparator;}
serializedString+=key+keyValueSeparator+map[key];}
return serializedString;}
Map.prototype.toJSON=function(object){
var JSONString="";
if(typeof(object)=="undefined"){JSONString+="undefined";
}else if(typeof(object)=="string"){JSONString+="\""+object+"\"";
}else if(typeof(object)=="number"||typeof(object)=="boolean"){JSONString+=object;
}else if(object[0]!=undefined){JSONString+="["
for(var index in object){if(typeof(object[index])!="undefined"&&typeof(object[index])!="function"){JSONString+=(index>0?",":"")+this.toJSON(object[index]);}}
JSONString+="]"
}else if(typeof(object)=="object"){JSONString+="{"
for(var key in object){if(typeof(object[key])!="undefined"&&typeof(object[key])!="function"){JSONString+=(JSONString!="{"?",":"")+"\""+key+"\":"+this.toJSON(object[key]);}}
JSONString+="}";}
return JSONString;}
Map.prototype.getClone=function(map){
var cloneMap=new Array();
for(var key in map){
if(typeof(map[key])=="object"){cloneMap[key]=this.getClone(map[key]);}else{cloneMap[key]=map[key];}}
return cloneMap}
Map.prototype.isEmpty=function(map){
map=(map!=undefined?map : this.array);
var isEmpty=true;
for(index in map){isEmpty=false;break;}
return isEmpty;}
Map.prototype.flatten=function(map,flattenedMap,keyPrefix){
flattenedMap=(flattenedMap==undefined?new Array(): flattenedMap);
for(var key in map){
if(typeof(map[key])=="object"||typeof(map[key])=="array"){flattenedMap=this.flatten(map[key],flattenedMap,(keyPrefix!=undefined?keyPrefix+"/" : "")+key);}else{flattenedMap[(keyPrefix!=undefined?keyPrefix+"/" : "")+key]=map[key];}}
return flattenedMap;}
Map.prototype.putAll=function(firstMap,secondMap){
secondMap=(secondMap!=undefined?secondMap : this.array);
var mergedMap=new Array();
for(key in firstMap){mergedMap[key]=firstMap[key];}
for(key in secondMap){mergedMap[key]=secondMap[key];}
return mergedMap;}
Map.prototype.getMapFromString=function(string,pairSeperator,keyValueSeparator){
var map=new Array();var keyValueArray=undefined;var key="";var value="";
pairSeperator=(pairSeperator!=undefined?pairSeperator : ",");keyValueSeparator=(keyValueSeparator!=undefined?keyValueSeparator : "=");
pairArray=string.split(pairSeperator);
for(var i=0;i<pairArray.length;i++){
keyValueArray=pairArray[i].split(keyValueSeparator);
if(keyValueArray[0]!=undefined&&keyValueArray[0]!=""&&keyValueArray[1]!=undefined){map[keyValueArray[0]]=keyValueArray[1];}}
return map;}
Map.prototype.toArray=function(map){
map=(map!=undefined?map : this.array);var resultArray=new Array();
for(var key in map){resultArray[resultArray.length]=[key,map[key]];}
return resultArray;}
Map.prototype.toMap=function(array,valueSeparator){
var newMap=new Array();
if(valueSeparator==undefined){
for(var index in array){
newMap[array[index]]=index;}
}else{
var keyValue=undefined;
for(var index in array){keyValue=array[index].split(valueSeparator);newMap[keyValue[0]]=keyValue[1];}}
return newMap;}
Map.prototype.isMapEquals=function(map1,map2,keyValidationArray){
var isEqual=(map1==undefined||map2==undefined?false : true);
if(isEqual&&keyValidationArray!=undefined){
for(var index in keyValidationArray){if(map1[keyValidationArray[index]]!=map2[keyValidationArray[index]]){isEqual=false;break;}}
}else{if(isEqual){for(var key in map1){if(map1[key]!=map2[key]){isEqual=false;break;}}}
if(isEqual){for(var key in map2){if(map2[key]!=map1[key]){isEqual=false;break;}}}}
return isEqual;}
Map.prototype.isArrayContentEquals=function(array1,array2){
var result=true;var map2=MapUtils.toMap(array2);
if(array1.length!=array2.length){result=false;}else{for(var index in array1){
if(map2[array1[index]]==undefined){result=false;break;}}}
return result;}
var MapUtils=new Map();
function ResourceController(id){
this.id=id;}
ResourceController.id="ResourceController";ResourceController._defaultMap=undefined;ResourceController._environmentMap=undefined;ResourceController._skinMap=undefined;ResourceController.environmentResourceName="";ResourceController.skinResourceName="";
ResourceController.prototype.init=function(){
Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);
this._defaultMap=(typeof(defaultProductResourceMap)!="undefined"?defaultProductResourceMap : new Array());this.loadProperties();}
ResourceController.prototype.get=function(key,defaultValue){
var value=undefined;
value=MapUtils.get(key,this._skinMap,undefined);if(value==undefined){
value=MapUtils.get(key,this._environmentMap,undefined);if(value==undefined){
value=MapUtils.get(key,this._defaultMap,undefined);}}
if(value!=undefined){return value;}else{return(defaultValue!=undefined?defaultValue : "");}}
ResourceController.prototype.loadProperties=function(){
if(environmentConfigMap!=undefined&&globalResourceMap!=undefined){
this._environmentMap=environmentConfigMap;this._skinMap=globalResourceMap;
Workspace.events.throwEvent(Workspace.events.EVENT_RESOURCES_LOADED,this);
}else{if(environmentConfigMap==undefined){this.environmentResourceUrl="/environment/"+(Workspace.query.locale!=undefined?Workspace.query.locale+"/" : "")+Workspace.retailerCode+".js";this.sendRequest(this.environmentResourceUrl,[]);}else{this._environmentMap=environmentConfigMap;}
if(globalResourceMap==undefined){this.skinResourceUrl="/pages/"+Workspace.skin+"/properties.js";this.sendRequest(this.skinResourceUrl,[]);}else{this._skinMap=globalResourceMap;}}}
ResourceController.prototype.applyProperties=function(prefixKey,object){
var attributeValue=undefined;
for(attribute in object){
if(typeof(object[attribute])!="function"){attributeValue=this.get(object.id+"Properties/"+attribute,"UNDEFINED_PROPERTY");if(attributeValue!="UNDEFINED_PROPERTY"){object[attribute]=attributeValue;}}}
for(var key in Workspace.query){
if(key.indexOf(object.id+"_")==0){try{
value=decodeURIComponent(Workspace.query[key]);value=value.replace(/\$/g,"\"");value=value.replace(/\(/g,"{");value=value.replace(/\)/g,"}");value=value.replace(/\+/g,":");
if(value.indexOf("{")==0){value="["+value+"]";eval(key.replace("_",".")+"=eval("+value+")[0]");
}else{eval(key.replace("_",".")+"=eval("+value+")");}
}catch(e){log.error("Failed url property override for "+key,this);}}}}
ResourceController.prototype.sendRequest=function(url,params){
det.sendRequest({method:"GET",serverUrl:url,responseFormat:det.RESPONSE_FORMAT_TEXT,callingController:this});}
ResourceController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED&&attributes!=undefined&&attributes.response!=undefined&&attributes.callingController==this){
if(attributes.serverUrl==this.environmentResourceUrl){
if(attributes.response["textResponse"].indexOf("environmentConfigMap")>-1){eval(attributes.response["textResponse"]);
}else{log.info("No ENVIRONMENT resource file was found");environmentConfigMap=new Array();}
this._environmentMap=environmentConfigMap;
}else if(attributes.serverUrl==this.skinResourceUrl){
if(attributes.response["textResponse"].indexOf("globalResourceMap")>-1){eval(attributes.response["textResponse"]);
}else{log.info("No SKIN resource file was found");globalResourceMap=new Array();}
this._skinMap=globalResourceMap;}
if(this._environmentMap!=undefined&&this._skinMap!=undefined){Workspace.events.throwEvent(Workspace.events.EVENT_RESOURCES_LOADED,this);}}}
var resource=new ResourceController("resource");
function SessionController(id){
this.id=id;}
SessionController.prototype.id="SessionController";SessionController.prototype.handlerUrl=undefined;SessionController.prototype.clientSessionTime=14400;SessionController.prototype.serverSessionTime=1800;SessionController.prototype.timeBeforeWarningTimemout=60;
SessionController.prototype.keepAliveCallThread=undefined;SessionController.prototype.keepAliveCheckThread=undefined;SessionController.prototype.keepAliveCallFrequency=100000;SessionController.prototype.keepAliveCheckFrequency=20000;SessionController.prototype.sessionTimeoutMessageBox=undefined;SessionController.prototype.requestTimestamp=undefined;SessionController.prototype.clientSessionTimestamp=undefined;SessionController.prototype.isLoggingEnabled=true;
SessionController.prototype.init=function(){
resource.applyProperties(this.id+"Properties",this);
Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);
this.handlerUrl=Workspace.serverContext;}
SessionController.prototype.callKeepAlive=function(){
det.sendRequest({action:"keepAlive",serverUrl:this.handlerUrl+"/action/keepAlive",
method:"POST",callingController:this});
}
SessionController.prototype.enableKeepAlive=function(){
if(this.keepAliveCallThread==undefined){this.clientSessionTimestamp=new Date();this.keepAliveCallThread=setTimeout(this.id+".callKeepAlive();",this.keepAliveCallFrequency);this.keepAliveCheckThread=setTimeout(this.id+".checkSession();",this.keepAliveCheckFrequency);}}
SessionController.prototype.disableKeepAlive=function(){
if(this.keepAliveCallThread!=undefined){
clearTimeout(this.keepAliveCallThread);clearTimeout(this.keepAliveCheckThread);this.keepAliveCallThread=undefined;this.keepAliveCheckThread=undefined;}}
SessionController.prototype.checkSession=function(){
var clientTime=(new Date())-this.clientSessionTimestamp;
if(this.isLoggingEnabled==true){log.debug("keepAlive: * idle Time: "+clientTime / 1000+
"-clientSessionTime: "+this.clientSessionTime+
"-serverSessionTime: "+this.serverSessionTime+
"-timeBeforeWarningTimeout: "+this.timeBeforeWarningTimemout+
"-keepAliveCallFrequency: "+this.keepAliveCallFrequency / 1000,this);}
if(clientTime>=(this.clientSessionTime-this.timeBeforeWarningTimemout)* 1000){if(this.sessionTimeoutMessageBox==undefined){this.sessionTimeoutMessageBox=Workspace.message.displayMessage({"message":"You session will expire in "+this.timeBeforeWarningTimemout+" seconds.<BR>Click ok if you want to continue using the application.","templateId":"messageConfirmationTemplate","duration":0,"jsActionYes":this.id+".restartKeepAliveThread();Workspace.message.hide('"+"messageObject"+Workspace.message.messageObjectCount+"');"+this.id+".sessionTimeoutMessageBox=undefined","jsActionNo":this.id+".callTimeoutPage('UserForcedExpiration');Workspace.message.hide('"+"messageObject"+Workspace.message.messageObjectCount+"');"+this.id+".sessionTimeoutMessageBox=undefined","isClosableOnClick":false});}}
if(clientTime>=this.clientSessionTime * 1000){
this.callTimeoutPage("ExpiredFromInactivity");}
if(this.keepAliveCheckThread!=undefined){this.keepAliveCheckThread=setTimeout(this.id+".checkSession();",this.keepAliveCheckFrequency);}}
SessionController.prototype.callTimeoutPage=function(contextualText){
this.disableKeepAlive();Workspace.callUrl(resource.get("TIMEOUT_URL")+"#"+contextualText);}
SessionController.prototype.restartKeepAliveThread=function(){
this.disableKeepAlive();this.enableKeepAlive();}
SessionController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED){
if(attributes!=undefined&&attributes.response!=undefined){
if(attributes.response["keepAliveSession"]!=undefined){
this.serverSessionTime=parseInt(attributes.response["keepAliveSession"]["maxInactiveInterval"]);this.keepAliveCallFrequency=this.serverSessionTime * 0.75 * 1000;
if(this.keepAliveCallThread!=undefined){clearTimeout(this.keepAliveCallThread);this.keepAliveCallThread=setTimeout(this.id+".callKeepAlive();",this.keepAliveCallFrequency);}
}else{
if(this.keepAliveCallThread!=undefined&&attributes.serverUrl!=undefined){if(attributes.serverUrl.indexOf(Workspace.serverContext)>-1){this.restartKeepAliveThread();}}
}}}}
function StateController(id){
this.id=id;}
StateController.prototype.keyPrefix=undefined;
StateController.prototype.init=function(){
resource.applyProperties(this.id+"Properties",this);}
StateController.prototype.set=function(key,value){
var keyPrefix="";
if(this.keyPrefix!=undefined){keyPrefix=ParserUtils.parseHtml(this.keyPrefix[key]!=undefined?this.keyPrefix[key] : this.keyPrefix["default"]);}
CookieUtils.setAttribute(keyPrefix+key,value,true);}
StateController.prototype.get=function(key){
var keyPrefix="";
if(this.keyPrefix!=undefined){keyPrefix=ParserUtils.parseHtml(this.keyPrefix[key]!=undefined?this.keyPrefix[key] : this.keyPrefix["default"]);}
return CookieUtils.getAttribute(keyPrefix+key);}
var State=new StateController("State");
function StringParser(id){
this.id=id;}
StringParser.prototype.id="StringParser";StringParser.prototype.templateCache=new Array();StringParser.prototype.serializerAttributes={keyValueSeparator:":",pairSeparator:",",arrayOpeningSeparator:"[",arrayClosingSeparator:"]",mapOpeningSeparator:"{",mapClosingSeparator:"}",stringOpeningSeparator:"\"",stringClosingSeparator:"\"",isShowArrayIndex:false,isIndentByLevel:false,isParseControllers:false,isParseFunctions:false,maxRecursionLevel:5}
StringParser.prototype.externalTemplateAttribute=undefined;StringParser.prototype.waitingList=new Array();StringParser.prototype.counter=0;StringParser.prototype.index=0;StringParser.prototype.key="";
StringParser.prototype.applyTemplate=function(templateElementId,containerElementId,attributes,onComplete){
if(this.getTemplateHtml(templateElementId)==undefined){
if(this.waitingList[templateElementId]==undefined){this.waitingList[templateElementId]=new Array();}
this.waitingList[templateElementId].push({"functionName":"applyTemplate","containerElementId":containerElementId,"attributes":attributes,"onComplete":onComplete});
this.loadTemplate(templateElementId);
}else{var onCompleteScript=(onComplete!=undefined?"<script>"+onComplete+"</script>" : "");this.setContainerHtml(containerElementId,this.parseHtml(this.templateCache[templateElementId]+onCompleteScript,attributes));}}
StringParser.prototype.preloadTemplate=function(templateElementId,onComplete){
if(this.templateCache[templateElementId]==undefined){
if(this.waitingList[templateElementId]==undefined){this.waitingList[templateElementId]=new Array();}
this.waitingList[templateElementId].push({"functionName":"preloadTemplate","onComplete":onComplete});
this.loadTemplate(templateElementId,onComplete);}else if(onComplete!=undefined){eval(onComplete);}}
StringParser.prototype.onTemplateLoaded=function(templateElementId){
if(this.waitingList[templateElementId]!=undefined){
for(var index in this.waitingList[templateElementId]){
var requestInfo=this.waitingList[templateElementId][index];
if(requestInfo["functionName"]=="applyTemplate"){this.applyTemplate(templateElementId,requestInfo["containerElementId"],requestInfo["attributes"],requestInfo["onComplete"]);}else if(requestInfo["functionName"]=="preloadTemplate"){if(requestInfo["onComplete"]!=undefined){eval(requestInfo["onComplete"]);}
}}
this.waitingList[templateElementId]=new Array();}}
StringParser.prototype.loadTemplate=function(templateElementId,onComplete){
var templateUrl=Workspace.templatePath+"/"+templateElementId+".html";
if(typeof(Workspace)!="undefined"&&Workspace.events!=undefined&&!Workspace.events.isEventListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this)){Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);}
log.debug("importing template : "+templateUrl,this);
this.sendRequest(templateUrl,{"templateId":templateElementId,"onComplete":onComplete});}
StringParser.prototype.getTemplateHtml=function(templateElementId){
if(this.templateCache[templateElementId]!=undefined){return this.templateCache[templateElementId];
}else if(document.getElementById(templateElementId)!=undefined){this.templateCache[templateElementId]=this.cleanupHtml(document.getElementById(templateElementId).innerHTML).replace(/<!--TEMPLATE|TEMPLATE-->/g,"");return this.templateCache[templateElementId];}else{return undefined;}}
StringParser.prototype.setContainerHtml=function(containerElementId,html){
var element=document.getElementById(containerElementId);
if(element!=undefined){
if(element.value==undefined){element.innerHTML=html;}else{element.value=html;}
this.evalScriptTags(html);}else{log.error("setContainerHtml: Container element '"+containerElementId+"' is not found",this);}}
StringParser.prototype.cleanupHtml=function(html){
return html.replace(/[\n\r\t]/g," ");}
StringParser.prototype.appendContainerHtml=function(containerElementId,html){
var element=document.getElementById(containerElementId);
if(element!=undefined){
html=this.cleanupHtml(html);
if(element.value==undefined){element.innerHTML+=html;}else{element.value+=html;}
this.evalScriptTags(html);}else{log.error("setContainerHtml: Container element '"+containerElementId+"' is not found",this);}}
StringParser.prototype.evalScriptTags=function(html){
var scriptTagsArray=html.match(/<script>([^\<]*)<\/script>/g);
if(scriptTagsArray!=undefined&&scriptTagsArray.length>0){
for(var i=0;i<scriptTagsArray.length;i++){eval(scriptTagsArray[i].match(/<script>(.*)<\/script>/)[1]);}}}
StringParser.prototype.parseTemplate=function(templateElementId,attributes){
return this.parseHtml(this.getTemplateHtml(templateElementId),attributes);}
StringParser.prototype.parseHtml=function(html,attributes){
return this.parseHtmlScriptSnippets(this.parseTokens(this.parseStatements(html,attributes),attributes));}
StringParser.prototype.parseTokens=function(html,attributes){
var tokenArray=html.match(/@([^@]*)@/g);var completedTokenReplaceMap=new Array();var value=undefined;
if(tokenArray!=undefined){
for(var i=0;i<tokenArray.length;i++){
if(completedTokenReplaceMap[tokenArray[i]]==undefined){completedTokenReplaceMap[tokenArray[i]]=true;
value=MapUtils.getMapValue(tokenArray[i].match(/@(.*)@/)[1],attributes);
if(value!=undefined){html=html.replace(new RegExp(tokenArray[i],"g"),value);}}}}
return html;}
StringParser.prototype.fixString=function(string){
if(typeof(string)=="string"){return string.replace(/\&/g,"&amp;").replace(/\</g,"&lt;").replace(/\>/g,"&gt;").replace(/\"/g,"&quot;").replace(/\'/g,"&apos;").replace(/[\n\r]/g,"<br/>")}else{return string;}}
StringParser.prototype.parseHtmlScriptSnippets=function(html){
while(html.match(/\[\$([^\$]*)\$\]/m)){html=html.replace(/\[\$([^\$]*)\$\]/m,eval(html.match(/\[\$([^\$]*)\$\]/m)[1]));}
while(html.match(/\[\!([^\!]*)\!\]/m)){
eval(html.match(/\[\!([^\!]*)\!\]/m)[1]);
html=html.replace(/\[\!([^\!]*)\!\]/m,"");}
return html;}
StringParser.prototype.parseStatements=function(html,attributes){
var tmpString=undefined;var regExp=undefined;
var matchExpression=html.match(/\[([A-Z_]+\(.*\))(.*)\$\1\]/g);if(matchExpression!=undefined){
var tmpString="";for(var i=0;i<matchExpression.length;i++){
tmpString=matchExpression[i];
regExp=tmpString.match(/\[([^\(][A-Z\_]*)\(([^\$]*)\)\$(.*)\$\1\(\2\)\]/);
html=html.substr(0,html.indexOf(tmpString))+this.executeInstruction(regExp[1],this.parseTokens(regExp[2],attributes),regExp[3],attributes)+html.substr(html.indexOf(tmpString)+tmpString.length);}}
return html;}
StringParser.prototype.executeInstruction=function(instruction,parameters,content,attributes){
var newContent="";
if(attributes!=undefined){if(attributes["FOR_EACH_INDEX"]!=undefined){attributes["PARENT_FOR_EACH_INDEX"]=attributes["FOR_EACH_INDEX"];}
if(attributes["FOR_EACH_KEY"]!=undefined){attributes["PARENT_FOR_EACH_KEY"]=attributes["FOR_EACH_KEY"];}}
if(instruction.toUpperCase()=="FOR_EACH"){
var array=undefined;
try{array=MapUtils.get(parameters,attributes);
if(array==undefined){try{array=eval(parameters);}catch(e){array=undefined;}}}catch(e){log.error("Could not execute template instruction: "+instruction+"("+parameters+")",this);}
if(array!=undefined){
array=MapUtils.getClone(array);
var forEachAttributes=undefined;var iCount=0;
for(var key in array){
if(typeof(array[key])!="object"&&typeof(array[key])!="array"){forEachAttributes=new Array();forEachAttributes["FOR_EACH_VALUE"]=array[key];}else{forEachAttributes=array[key];}
forEachAttributes["PARENT_FOR_EACH_INDEX"]=(attributes!=undefined&&attributes["PARENT_FOR_EACH_INDEX"]!=undefined?attributes["PARENT_FOR_EACH_INDEX"] : undefined);forEachAttributes["PARENT_FOR_EACH_KEY"]=(attributes!=undefined&&attributes["PARENT_FOR_EACH_KEY"]!=undefined?attributes["PARENT_FOR_EACH_KEY"] : undefined);forEachAttributes["FOR_EACH_INDEX"]=iCount;forEachAttributes["FOR_EACH_KEY"]=key;
this.index=iCount;this.key=key;
newContent+=this.parseHtml(content,forEachAttributes);iCount++;}}
}else if(instruction.toUpperCase()=="LOOP"){
var count=0;var loopAttributes=new Array();
if(MapUtils.get(parameters,attributes)!=undefined){count=parseInt(MapUtils.get(parameters,attributes));}else{try{count=parseInt(eval(parameters));}catch(e){}}
for(var i=0;i<count;i++){newContent+=this.parseHtml(content,{"LOOP_INDEX":i,"LOOP_MAX":count});}
}else if(instruction.toUpperCase()=="IF"){
newContent="";
if(eval(this.parseTokens(parameters,attributes))==true){newContent=this.parseHtml(content,attributes);}
}else if(instruction.toUpperCase()=="IF_DEFINED"){
var isConditionMet=false;newContent="";
try{isConditionMet=(MapUtils.get(parameters,attributes)!=undefined);}catch(e){}
if(isConditionMet){newContent=this.parseHtml(content,attributes);}
}else if(instruction.toUpperCase()=="IF_NOT_DEFINED"){
var isConditionMet=false;newContent="";
try{isConditionMet=(MapUtils.get(parameters,attributes)==undefined);}catch(e){}
if(isConditionMet){newContent=this.parseHtml(content,attributes);}
}else if(instruction.toUpperCase()=="WITH"){
var object=undefined;newContent="";
try{object=eval(this.parseTokens(parameters,attributes));}catch(e){}
if(object!=undefined){newContent=this.parseHtml(content,MapUtils.putAll(attributes,MapUtils.flatten(object)));}
}else if(instruction.toUpperCase()=="INSERT_TEMPLATE"){
newContent=this.parseTemplate(parameters);}
return newContent;}
StringParser.prototype.serializeObject=function(object,attributes,level){
attributes=(attributes!=undefined?attributes : this.serializerAttributes);
if(level==undefined){level=0;}
var returnValue="";var objectToSerialize=undefined;
var spaces="";for(var sCount=0;sCount<level;sCount++){spaces+="   ";}
if(level<attributes["maxRecursionLevel"]){
if(typeof(object)=="undefined"||typeof(object)=="null"||typeof(object)=="unknown"||object==undefined||object==null){returnValue="null";
}else if(typeof(object)=="string"){returnValue=attributes["stringOpeningSeparator"]+object+attributes["stringClosingSeparator"];
}else if(typeof(object)=="number"){returnValue=object;
}else if(typeof(object)=="boolean"){returnValue=(object?"true" : "false");
}else if(typeof(object)=="function"){returnValue="[Function]";
}else if(typeof(object)=="object"){
if(object.length!=undefined&&object[0]!=undefined){
returnValue+=attributes["arrayOpeningSeparator"];
for(var index in object){
if(typeof(object[index])!="unknown"&&(attributes["isParseFunctions"]||(!attributes["isParseFunctions"]&&typeof(object[index])!="function"))){
if(level>0&&object[index]!=undefined&&object[index].id!=undefined&&!attributes["isParseControllers"]){objectToSerialize="<"+object[index].id+">";}else{objectToSerialize=object[index];}
returnValue+=(index>0?attributes["pairSeparator"] : "")+(attributes["isIndentByLevel"]?spaces : "")+(attributes["isShowArrayIndex"]==true?+index+attributes["keyValueSeparator"] : "")+
this.serializeObject(objectToSerialize,attributes,parseInt(level+1));}}
returnValue+=attributes["arrayClosingSeparator"];
}else{
returnValue+=attributes["mapOpeningSeparator"];
var mapIndex=0;
try{for(index in object){
if(typeof(object[index])!="unknown"&&(attributes["isParseFunctions"]||(!attributes["isParseFunctions"]&&typeof(object[index])!="function"))){
if(level>0&&object[index]!=undefined&&object[index].id!=undefined&&!attributes["isParseControllers"]){objectToSerialize="<"+object[index].id+">";}else{objectToSerialize=object[index];}
if(mapIndex>0){returnValue+=attributes["pairSeparator"];}
returnValue+=(attributes["isIndentByLevel"]?spaces : "")+index+attributes["keyValueSeparator"]+this.serializeObject(objectToSerialize,attributes,parseInt(level+1));mapIndex++;}}}catch(e){returnValue+="[could not parse object]";}
returnValue+=attributes["mapClosingSeparator"];}
}else{returnValue="<"+typeof(object)+">";}
}else{returnValue="[Maximum recursion level reached]";}
return returnValue;}
StringParser.prototype.sendRequest=function(action,infoMap){
det.sendRequest({method:"GET",responseFormat:det.RESPONSE_FORMAT_TEXT,serverUrl:action,action:action,info:infoMap,callingController:this});}
StringParser.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED&&attributes.callingController==this){if(attributes!=undefined&&attributes.response!=undefined){
if(attributes.responseFormat==det.RESPONSE_FORMAT_TEXT){
if(attributes.info["templateId"]!=undefined){
this.templateCache[attributes.info["templateId"]]=this.cleanupHtml(attributes.response["textResponse"]);
this.onTemplateLoaded(attributes.info["templateId"]);}}}}}
ParserUtils=new StringParser("ParserUtils");
var TemplateVar="";
function TrackerController(id){
this.id=id;}
TrackerController.prototype.id="TrackerController";TrackerController.prototype.trackerElementListList=undefined;TrackerController.prototype.trackerCount=2;TrackerController.prototype.trackerIndex=0;TrackerController.prototype.events=undefined;
TrackerController.prototype.init=function(){
resource.applyProperties(this.id+"Properties",this);
for(var eventId in this.events){Workspace.events.addListener(eventId,this);}
this.trackerElementList=new Array();for(var i=0;i<3;i++){this.trackerElementList[i]=document.createElement("img");this.trackerElementList[i].id=this.id+"Image"+i;this.trackerElementList[i].display="none";this.trackerElementList[i].src="/images/spacer.gif";}
Workspace.events.throwEvent(Workspace.events.EVENT_CONTROLLER_INITIALIZED,this);}
TrackerController.prototype.call=function(eventKey,attributes){
var trackerUrl="";
if(this.events[eventKey]!=undefined){
for(var index in this.events[eventKey]){
if(this.events[eventKey][index].indexOf("js:")==0){
eval(this.events[eventKey][index].substring(3));
}else if(this.events[eventKey][index].indexOf("url:")==0){
trackerUrl=ParserUtils.parseHtml(this.events[eventKey][index].substring(4),attributes);
this.trackerElementList[this.trackerIndex].src=trackerUrl+(trackerUrl.indexOf("?")>-1?"&":"?")+"rnd="+Math.random();
this.trackerIndex++;if(this.trackerIndex>this.trackerCount){this.trackerIndex=0;}}}}}
TrackerController.prototype.customCall=function(trackerUrl){
this.trackerElementList[this.trackerIndex].src=trackerUrl;log.debug("["+eventKey+"] called url: "+trackerUrl,this);
this.trackerIndex++;if(this.trackerIndex>this.trackerCount){this.trackerIndex=0;}}
TrackerController.prototype.catchEvent=function(eventKey,attributes){
this.call(eventKey,attributes);}
function UserController(pId,parentClass){
this.id=pId;this.parentClass=parentClass;
return this;}
UserController.prototype.id="UserController";UserController.prototype.handlerUrl="";UserController.prototype.parentClass=undefined;UserController.prototype.username="";UserController.prototype.userId=undefined;UserController.prototype.isSignedIn=false;UserController.prototype.isAuthenticated=false;UserController.prototype.isRememberMeSettingActive=false;UserController.prototype.elementId="authenticateDialog";UserController.prototype.usernameElementId="authenticateUsername";UserController.prototype.passwordElementId="authenticatePassword";UserController.prototype.defaultLocale="en-us";UserController.prototype.lastSigninType=undefined;
UserController.prototype.init=function(){
this.handlerUrl=Workspace.serverContext+"/action/identity";
Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);Workspace.events.addListener(Workspace.events.EVENT_PAGE_LOADED,this);}
UserController.prototype.updateState=function(dataMap){
if(dataMap!=undefined){
var previousState_isSignedIn=(this.isSignedIn?true : false);var previousState_isAuthenticated=(this.isAuthenticated?true : false);
if(dataMap["profileInfo"]!=undefined){
this.userId=dataMap["profileInfo"]["signInID"];
if(CookieUtils.getAttribute("rememberMeCookie")!=undefined){
rememberMeCookie=CookieUtils.getAttribute("rememberMeCookie").split("&");
for(var settingIndex in rememberMeCookie){if(rememberMeCookie[settingIndex].indexOf("=")>0){if(rememberMeCookie[settingIndex].split("=")[0].indexOf(Workspace.population+"_active")>-1){this.isRememberMeSettingActive=(rememberMeCookie[settingIndex].split("=")[1]=="1"?true : false);break;}}}}
this.username=dataMap["profileInfo"]["loginName"];
this.setRememberMeCookie(this.isRememberMeSettingActive);}else{
if(CookieUtils.getAttribute("rememberMeCookie")!=undefined){
rememberMeCookie=CookieUtils.getAttribute("rememberMeCookie").split("&");
for(var settingIndex in rememberMeCookie){
if(rememberMeCookie[settingIndex].indexOf("=")>0){
if(rememberMeCookie[settingIndex].split("=")[0].indexOf(Workspace.population+"_id")>-1){this.userId=rememberMeCookie[settingIndex].split("=")[1];}else if(rememberMeCookie[settingIndex].split("=")[0].indexOf(Workspace.population+"_active")>-1){
this.isRememberMeSettingActive=(rememberMeCookie[settingIndex].split("=")[1]=="1"?true : false);}else if(rememberMeCookie[settingIndex].split("=")[0].indexOf(Workspace.population+"_username")>-1){this.username=rememberMeCookie[settingIndex].split("=")[1];}}}}}
if(dataMap["isSignedIn"]!=undefined){this.isSignedIn=(dataMap["isSignedIn"]=="true"?true : false);}
if(dataMap["isAuthenticated"]!=undefined){this.isAuthenticated=(dataMap["isAuthenticated"]=="true"?true : false);}
if(this.isRememberMeSettingActive&&this.isSignedIn&&!this.isAuthenticated){this.lastSigninType="autoSignin";}
if(previousState_isSignedIn!=this.isSignedIn||previousState_isAuthenticated!=this.isAuthenticated){Workspace.events.throwEvent(Workspace.events.EVENT_USER_STATE_CHANGE,this);}
if(!previousState_isSignedIn&&this.isSignedIn){Workspace.events.throwEvent(Workspace.events.EVENT_USER_SIGNIN,this);
}else if(!previousState_isAuthenticated&&this.isAuthenticated){Workspace.events.throwEvent(Workspace.events.EVENT_USER_AUTHENTICATED,this);}
if(previousState_isSignedIn&&!this.isSignedIn){Workspace.events.throwEvent(Workspace.events.EVENT_USER_SIGNOUT,this);}
if(dataMap["mobilityCase"]!=undefined&&resource.get(dataMap["mobilityCase"])!=undefined&&State.get("mobilityMessageDisplayed")==undefined){
State.set("mobilityMessageDisplayed","1");Workspace.message.displayMessage(resource.get(dataMap["mobilityCase"]));}}}
UserController.prototype.displayAuthentication=function(){
if(document.getElementById(this.usernameElementId)!=undefined){document.getElementById(this.usernameElementId).innerHTML=this.username;}
if(document.getElementById(this.elementId)!=undefined){Anim.openSingle(this.elementId);}}
UserController.prototype.submitAuthentication=function(){
var password="";
if(document.getElementById(this.passwordElementId)!=undefined){
password=document.getElementById(this.passwordElementId).value;
if(password!=""){this.lastSigninType="signInPassword";this.sendRequest("signInPassword",[["SigninName",this.username],["Password",password],["lastSigninType",this.lastSigninType]]);}else if(password.length==0){
Workspace.message.displayMessage("Please specify a password");}}}
UserController.prototype.signout=function(isClearCookies){
if(isClearCookies){this.setRememberMeCookie(false);CookieUtils.deleteCookie("userCredentials");}
this.lastSigninType="signOut";this.sendRequest("signOut",undefined);}
/**
* Signs in the user with a username/password
*/
UserController.prototype.signin=function(attributes,isForgotPasswordSignin){
isForgotPasswordSignin=isForgotPasswordSignin!=undefined?isForgotPasswordSignin:false;
var action="";
if(attributes["SigninName"]!=""&&attributes["Password"]!=""&&!isForgotPasswordSignin){action="signInPassword";
}else if(attributes["SigninName"]!=""&&attributes["Email"]!=""&&attributes["HintAnswer"]!=""){action="signInAnswer";}
this.lastSigninType=action;attributes[attributes.length]={"lastSigninType":action};this.sendRequest(action,MapUtils.toArray(attributes));}
/**
* Handles the setting/removal of the rememberMeCookie setting
*/
UserController.prototype.setRememberMeCookie=function(isActive){
var rememberMeCookie=undefined;
if(CookieUtils.getAttribute("rememberMeCookie")!=undefined){rememberMeCookie=CookieUtils.getAttribute("rememberMeCookie").split("&");}else{rememberMeCookie=new Array();rememberMeCookie[rememberMeCookie.length]="";}
this.isRememberMeSettingActive=isActive;
var isUpdated=false;
for(var settingIndex in rememberMeCookie){
if(rememberMeCookie[settingIndex].indexOf("=")>0){
if(rememberMeCookie[settingIndex].split("=")[0]==Workspace.population+"_id"){rememberMeCookie[settingIndex]=Workspace.population+"_id="+this.userId;isUpdated=true;}else if(rememberMeCookie[settingIndex].split("=")[0]==Workspace.population+"_active"){rememberMeCookie[settingIndex]=Workspace.population+"_active="+(isActive?"1":"0");isUpdated=true;}else if(rememberMeCookie[settingIndex].split("=")[0]==Workspace.population+"_username"){rememberMeCookie[settingIndex]=Workspace.population+"_username="+this.username;isUpdated=true;}}}
if(!isUpdated){rememberMeCookie[rememberMeCookie.length]=Workspace.population+"_id="+this.userId;rememberMeCookie[rememberMeCookie.length]=Workspace.population+"_active="+(isActive?"1":"0");rememberMeCookie[rememberMeCookie.length]=Workspace.population+"_username="+this.username;}
CookieUtils.setAttribute("rememberMeCookie",rememberMeCookie.join("&"));
CookieUtils.setAttribute("rememberMe","&id="+this.userId+"&active="+(isActive?"1":"0"));}
UserController.prototype.getBrowserLocale=function(){
var locale=this.defaultLocale;
if(navigator.userLanguage!=undefined){locale=navigator.userLanguage.toLowerCase();
}else if(navigator.userAgent.match(/[\;](..\-..)[\;|]/)){locale=RegExp.$1.toLowerCase();}
return locale;}
UserController.prototype.sendRequest=function(pActionType,pParams,handlerUrl){
handlerUrl=(handlerUrl!=undefined?handlerUrl : this.handlerUrl);
var requestParams=new Array();
if(pParams!=undefined){requestParams=requestParams.concat(pParams);}
det.sendRequest({serverUrl:Workspace.serverContext+"/action/"+pActionType,action:pActionType,parameters:requestParams,callingController:this});}
UserController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED){
if(attributes.response!=undefined){
if(attributes.response["errorCode"]=="IDENTITY.SigninDoesNotExist"||
attributes.response["errorCode"]=="InvalidLoginException"){
if(attributes.action=="signInAnswer"){this.lastSigninType="forgotPassword";Workspace.message.displayMessage(resource.get("Signin.InvalidForgotPassword"));}else if(attributes.action=="signInPassword"){Workspace.message.displayMessage(resource.get("Signin.InvalidUserPassword"));}else if(attributes.action=="getSecretQuestion"){Workspace.message.displayMessage(resource.get("Signin.DoesNotExist"));}}
if(attributes.response["isSignedIn"]!=undefined&&attributes.response["isAuthenticated"]!=undefined){
if(!this.isAuthenticated&&attributes.response["isAuthenticated"]=="true"){Anim.reset("authenticateDialog");}
if(attributes.response["profileInfo"]!=undefined){this.userId=attributes.response["profileInfo"]["signInID"];this.username=attributes.response["profileInfo"]["loginName"];}
if(attributes.response["errorMessage"]!=undefined){Workspace.message.displayMessage(attributes.response["errorMessage"]);}
if(attributes.action=="signInAnswer"){this.lastSigninType="forgotPassword";}
if(Workspace.isControllersInitialized){this.updateState(attributes.response);}
}else if(attributes.callingController==this&&attributes.response["errorCode"]=="FS-19000"){Workspace.message.displayMessage(resource.get("IDTP-02003"));}}}}
function WorkspaceController(id){
this.id=id;this.getEnvironmentSettings();
if(typeof(EventController)!="undefined"){this.events=new EventController(this.id+".events");
this.events.addListener(this.events.EVENT_SERVER_RESPONSE_RECEIVED,this);this.events.addListener(this.events.EVENT_SERVER_REQUEST_SENT,this);this.events.addListener(this.events.EVENT_SERVER_ALL_REQUESTS_COMPLETED,this);this.events.addListener(this.events.EVENT_MODEL_IMAGE_LOADING,this);this.events.addListener(this.events.EVENT_MODEL_IMAGE_CHANGED,this);this.events.addListener(this.events.EVENT_RESOURCES_LOADED,this);this.events.addListener(this.events.EVENT_INITIALIZED,this);this.events.addListener(this.events.EVENT_CONTROLLER_INITIALIZED,this);this.events.addListener(this.events.EVENT_COOKIE_CHANGED,this);}
if(typeof(UserController)!="undefined"){this.user=new UserController(this.id+".user",this);}
if(typeof(MessageController)!="undefined"){this.message=new MessageController(this.id+".message",this);}
if(typeof(SessionController)!="undefined"){this.session=new SessionController(this.id+".session",this);}
return this;}
WorkspaceController.prototype.isInitialized=false;WorkspaceController.prototype.isSkinLoaded=false;WorkspaceController.prototype.isSessionInitialized=false;WorkspaceController.prototype.isControllersInitialized=false;WorkspaceController.prototype.isDisplaySplash=false;WorkspaceController.prototype.isPopulationChange=false;WorkspaceController.prototype.viewData=new Array();WorkspaceController.prototype.user=undefined;WorkspaceController.prototype.message=undefined;WorkspaceController.prototype.session=undefined;WorkspaceController.prototype.events=undefined;WorkspaceController.prototype.serverContext="";WorkspaceController.prototype.retailerCode="";WorkspaceController.prototype.population="";WorkspaceController.prototype.skin="";WorkspaceController.prototype.skinPath=undefined;WorkspaceController.prototype.templatePath=undefined;WorkspaceController.prototype.skinUrl="";WorkspaceController.prototype.cssUrl="";WorkspaceController.prototype.splashUrl="";WorkspaceController.prototype.libUrl="";WorkspaceController.prototype.query=undefined;WorkspaceController.prototype.waitElementId="waitElement";WorkspaceController.prototype.importHTMLToElementId="pageContainer";WorkspaceController.prototype.importReferenceController=undefined;WorkspaceController.prototype.fatalErrorCodes="";WorkspaceController.prototype.lastOpenedPopup=undefined;WorkspaceController.prototype.width=0;WorkspaceController.prototype.height=0;WorkspaceController.prototype.initializedControllersMap=undefined;WorkspaceController.prototype.controllerInitOrder=undefined;WorkspaceController.prototype.controllerClassMap=undefined;WorkspaceController.prototype.controllerClassDependency=undefined;WorkspaceController.prototype.initThread=undefined;WorkspaceController.prototype.isNewSession=true;WorkspaceController.prototype.libServerUrl="";
WorkspaceController.prototype.ERROR_SESSION_TIMEOUT="SESSION_TIME_OUT.SessionTimeOut";
WorkspaceController.prototype.onLoad=function(){
log.info("onLoad event caught",this);
this.width=parseInt(document.body.clientWidth);this.height=parseInt((document.body.clientHeight>0?document.body.clientHeight : document.documentElement.clientHeight));
resource.init();}
WorkspaceController.prototype.init=function(){
Workspace.session.init();
if(this.query.log=="debug"){this.importClass("LogController","log.init()");}
resource.applyProperties(this.id+"Properties",this);
this.initializedControllersMap=new Array();
State.init();
if(this.user!=undefined){this.user.init();}
if(typeof(Items)!="undefined"){Items.init();}
this.message.init();
log.info("Workspace is initialized",this);
if(this.isDisplaySplash&&State.get("splashDisplayed")==undefined&&(this.query.param1==undefined||this.query.param1=="")&&this.query.pop==undefined&&this.user.isSignedIn==false){this.loadSplash();}else{
if(!CookieUtils.isCookieSupported){this.message.displayMessage({message:resource.get("cookiesNotSupported")});}
this.importLib(this.libUrl);this.initServerSession();}}
WorkspaceController.prototype.initCompleted=function(attributes){
if(attributes!=undefined){this.viewData=attributes.response;}
if(document.cookie.indexOf("JSESSIONID")==-1){loopUntil("document.cookie.indexOf('JSESSIONID')>-1",this.id+".initCompleted()")
}else{
this.session.enableKeepAlive();
if(!this.isSessionInitialized){
this.isSessionInitialized=true;this.events.throwEvent(this.events.EVENT_INITIALIZED,this);this.loadSkin();}}}
WorkspaceController.prototype.initServerSession=function(){
log.debug("Initializing server session",this);
var params=new Array();
if(this.query.sid!=undefined){params[params.length]=["sid",this.query.sid];}
if(this.query.param1!=undefined){params[params.length]=["param1",this.query.param1];}
if(this.query.param2!=undefined){params[params.length]=["param2",this.query.param2];}
if(this.query.param3!=undefined){params[params.length]=["param3",this.query.param3];}
/*var startupDefaultType=(this.query.DEFAULT_TYPE!=undefined?this.query.DEFAULT_TYPE : resource.get("ModelProperties/defaultType"));if(startupDefaultType!=""&&startupDefaultType!=State.get("startupDefaultType")){params[params.length]=["DEFAULT_TYPE",startupDefaultType];State.set("startupDefaultType",startupDefaultType);}*/
if(resource.get("ModelProperties/drMode")!=""&&resource.get("ModelProperties/drMode")!=undefined){params[params.length]=["drMode",resource.get("ModelProperties/drMode")];}
if(this.query.c!=undefined){params[params.length]=["c",this.query.c];params[params.length]=["p",this.query.p];}else{
if(CookieUtils.getAttribute("initPop_"+this.population)!="true"){this.isPopulationChange=true;CookieUtils.setAttribute("initPop_"+this.population,"true",true);}
params[params.length]=["pop",this.population];params[params.length]=["roc",this.retailerCode];}
det.sendRequest({action:"init",serverUrl:this.serverContext+"/action/init",parameters:params,method:"POST",callingController:this});}
WorkspaceController.prototype.getEnvironmentSettings=function(){
this.query=getQuery();
if(this.query.serverContext!=undefined){this.serverContext=this.query.serverContext;}else if(typeof(SERVER_CONTEXT)!="undefined"){this.serverContext=SERVER_CONTEXT;}
if(this.query.roc!=undefined){this.retailerCode=this.query.roc;}else if(typeof(RETAILER_CODE)!="undefined"){this.retailerCode=RETAILER_CODE;}
if(this.query.pop!=undefined){this.population=this.query.pop.toUpperCase();}else if(this.query.p!=undefined){this.population=this.query.p.toUpperCase();}else if(typeof(DOMAIN)!="undefined"){this.population=DOMAIN;}
if(this.query.skin!=undefined){this.skin=this.query.skin;}else if(typeof(SKIN)!="undefined"){this.skin=SKIN;}else{this.skin=this.retailerCode;}
if(this.skinPath==undefined){this.skinPath="/pages/"+this.skin;}
if(this.templatePath==undefined){this.templatePath=this.skinPath+"/templates";}
this.skinUrl=this.skinPath+"/layout.html"+(this.query.log!=undefined?"?rnd="+Math.random(): "");this.cssUrl=this.skinPath+"/default.css";this.splashUrl=this.skinPath+"/splash.html"+(this.query.log!=undefined?"?rnd="+Math.random(): "");this.libUrl=this.skinPath+"/skin.js"+(this.query.log!=undefined?"?rnd="+Math.random(): "");}
WorkspaceController.prototype.initControllers=function(){
this.events.throwEvent(this.events.EVENT_SKIN_LOADED,this);
this.user.updateState(this.viewData);
this.controllerInitOrder=resource.get("ControllerInitOrder");this.controllerClassMap=resource.get("ControllerSelection");this.controllerClassDependency=resource.get("ClassDependency");
this.initController(0);}
WorkspaceController.prototype.initController=function(index){
if(this.controllerInitOrder.length>index){
this.activateController(
this.controllerInitOrder[index],this.controllerClassMap[this.controllerInitOrder[index]],escape(this.id+".initController("+parseInt(index+1)+")"));
}}
WorkspaceController.prototype.isControllerInitialized=function(controllerId){
return(this.initializedControllersMap[controllerId]!=undefined?true : false);}
WorkspaceController.prototype.showPanel=function(controllerId,onComplete){
log.debug("displaying controller "+controllerId+" panel");
this.activateController(
controllerId,this.controllerClassMap[controllerId],escape(controllerId+".show();"+(onComplete!=undefined?onComplete+";" : "")));}
WorkspaceController.prototype.activateController=function(controllerId,className,onInitCompleted){
className=(className!=undefined?className : this.controllerClassMap[controllerId]);
if(className!=undefined){
if(this.isControllerInstanciated(controllerId)&&onInitCompleted!=undefined){eval(unescape(onInitCompleted));
}else{
if(this.isClassLoaded(className)){
this.createController(
controllerId,className,escape(this.id+".activateController(\""+controllerId+"\",\""+className+"\",\""+(onInitCompleted)+"\")"));
}else{
this.importClass(
this.getClassDependency(className),escape(this.id+".activateController(\""+controllerId+"\",\""+className+"\",\""+(onInitCompleted)+"\")"));}}}else{log.error("Could not find class reference for controller: "+controllerId,this);eval(unescape(onInitCompleted));}}
WorkspaceController.prototype.isControllerInstanciated=function(controllerId){
var isControllerInstanciated=false;
try{if(typeof(eval(controllerId))=="object"){isControllerInstanciated=true;}}catch(e){}
return isControllerInstanciated;}
WorkspaceController.prototype.isClassLoaded=function(className){
var classNameArray=this.getClassDependency(className).split(",");
var isClassInScope=true;
for(var index in classNameArray){
try{if(!typeof(eval(classNameArray[index]))=="function"){isClassInScope=false;}
}catch(e){isClassInScope=false;}
if(!isClassInScope){break;}}
return isClassInScope;}
WorkspaceController.prototype.getClassDependency=function(className){
return className+(this.controllerClassDependency[className]!=undefined?","+this.controllerClassDependency[className] : "");}
WorkspaceController.prototype.createController=function(controllerId,className,onComplete){
log.debug("instanciating controller "+controllerId+" using class "+className,this);
var isActivatedSuccessfully=false;
eval(controllerId+"=new "+className+"('"+controllerId+"')");eval(controllerId+".init()");isActivatedSuccessfully=true;
if(isActivatedSuccessfully&&onComplete!=undefined){eval(unescape(onComplete));}}
WorkspaceController.prototype.controllerInitCompleted=function(){
this.isControllersInitialized=true;this.enableUserEvents();
this.isInitialized=true;
this.events.throwEvent(this.events.EVENT_PAGE_LOADED,this);}
WorkspaceController.prototype.enableUserEvents=function(){
if(document.getElementById("eventBlocker")!=undefined){log.info("Activating mouse events on page",this);document.getElementById("eventBlocker").style.display="none";}}
WorkspaceController.prototype.disableUserEvents=function(){
if(document.getElementById("eventBlocker")!=undefined){log.info("Deactivating mouse events on page",this);document.getElementById("eventBlocker").style.display="block";}}
WorkspaceController.prototype.importClass=function(classNames,onComplete){
var classIndex=-1;var classToLoad=undefined;var classNameArray=classNames.split(",");
while(classIndex<classNameArray.length&&classToLoad==undefined){
try{if(!typeof(eval(classNameArray[classIndex]))=="function"){classToLoad=classNameArray[classIndex];}}catch(e){classToLoad=classNameArray[classIndex];}
classIndex++;}
if(classToLoad!=undefined){
log.debug("importing class "+classToLoad,this);this.importLib("/js/"+(this.query.log=="debug"?"debug/" : "")+classToLoad+".js");
loopUntil("typeof("+classToLoad+")=='function'",escape(this.id+".importClass('"+classNames+"','"+onComplete+"')"),100);
}else{eval(unescape(onComplete));}}
WorkspaceController.prototype.importLib=function(libFilename,onComplete){
var headElement=document.getElementsByTagName("HEAD")[0];
var scriptElement=document.createElement("script");scriptElement.setAttribute("type","text/javascript");
scriptElement.setAttribute("src",this.libServerUrl+libFilename);
headElement.appendChild(scriptElement);
if(onComplete!=undefined){setTimeout(onComplete,500);}}
WorkspaceController.prototype.callUrl=function(url){
this.showWait();window.location.href=url;}
WorkspaceController.prototype.callUri=function(uri){
this.showWait();window.location.href=this.serverContext+uri;}
WorkspaceController.prototype.callUrlInParent=function(url){
if(window.opener!=undefined&&typeof(window.opener.location)!="unknown"){window.opener.location.href=url;window.opener.focus();
}else if(parent!=undefined&&typeof(parent.location)!="unknown"){parent.location.href=url
}else{this.callUrlInPopup(url);}}
WorkspaceController.prototype.callUrlIgnoreResponse=function(url){
var callingImg=new Image();callingImg.src=url;}
WorkspaceController.prototype.callUrlInPopup=function(url,title,windowAttributes){
this.lastOpenedPopup=window.open(url,title,windowAttributes);}
WorkspaceController.prototype.showWait=function(){
Anim.show(this.waitElementId);}
WorkspaceController.prototype.hideWait=function(){
Anim.hide(this.waitElementId);}
WorkspaceController.prototype.showDiscreetWait=function(){
Anim.show("discreetLoading");window.status="Loading...";}
WorkspaceController.prototype.hideDiscreetWait=function(){
Anim.hide("discreetLoading");window.status="";}
WorkspaceController.prototype.importHTML=function(sourceUrl,elementId,referenceController){
this.importHTMLToElementId=(elementId!=undefined?elementId : "pageContainer");this.importReferenceController=referenceController;
det.sendRequest({serverUrl:sourceUrl,method:"GET",responseFormat:det.RESPONSE_FORMAT_TEXT,callingController:this});}
WorkspaceController.prototype.loadSplash=function(){
this.setCSSFile(this.cssUrl);
log.debug("Loading splash page from: "+this.splashUrl,this);this.importHTML(this.splashUrl);this.enableUserEvents()
State.set("splashDisplayed","true");}
WorkspaceController.prototype.loadSkin=function(){
if(document.getElementById("pageLayout")==undefined){log.debug("Loading skin from: "+this.skinUrl,this);this.importHTML(this.skinUrl);}else{this.isSkinLoaded=true;
if(this.isSessionInitialized&&!this.isControllersInitialized){setTimeout(this.id+".initControllers()",1);}}
State.set("splashDisplayed","true");}
WorkspaceController.prototype.appendHTML=function(htmlSource,containerElementId){
ParserUtils.appendContainerHtml(containerElementId,htmlSource);log.info("HTML appended to "+containerElementId,this);}
WorkspaceController.prototype.setCSSFile=function(cssFilename){
var headElement=document.getElementsByTagName("HEAD")[0];
var linkElement=document.createElement("link");linkElement.setAttribute("rel","stylesheet");linkElement.setAttribute("type","text/css");linkElement.setAttribute("href",cssFilename);
headElement.appendChild(linkElement);}
WorkspaceController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==this.events.EVENT_SERVER_RESPONSE_RECEIVED){
if(attributes!=undefined&&attributes.response!=undefined){
if(attributes.response["message"]!=undefined&&attributes.response["message"]!=""){this.message.displayMessage(attributes.response["message"]);}
if(attributes.response["errorCode"]!=undefined&&attributes.response["errorCode"]!=""){
log.error("SERVER EXCEPTION: "+attributes.response["errorCode"]+" : "+attributes.response["errorMsg"],this);
if(this.fatalErrorCodes.indexOf(attributes.response["errorCode"])>-1&&attributes.action!="init"){this.session.callTimeoutPage(attributes.response["errorCode"]);}else if(resource.get(attributes.response["errorCode"])!=""){this.message.displayMessage({"message":resource.get(attributes.response["errorCode"]),"messageObjectId":"generalMessage"});}}
if(attributes.action=="init"){
if(attributes.response["errorCode"]==undefined){this.initCompleted(attributes);}else if(this.fatalErrorCodes.indexOf(attributes.response["errorCode"])>-1){this.events.throwEvent(this.events.EVENT_INIT_FAILURE,this);}}
}
}else if(eventKey==this.events.EVENT_RESOURCES_LOADED){this.init();
}else if(eventKey==this.events.EVENT_MODEL_IMAGE_LOADING||eventKey==this.events.EVENT_INITIALIZED){this.showWait();
}else if(eventKey==this.events.EVENT_MODEL_IMAGE_CHANGED){this.hideWait();
}else if(eventKey==this.events.EVENT_SERVER_REQUEST_SENT){this.showDiscreetWait();
}else if(eventKey==this.events.EVENT_SERVER_ALL_REQUESTS_COMPLETED){this.hideDiscreetWait();
}else if(eventKey==this.events.EVENT_CONTROLLER_INITIALIZED){
this.initializedControllersMap[attributes.id]=eval(attributes.id);
if(!this.isControllersInitialized){
var isAllInitialized=true;for(var index in this.controllerInitOrder){if(this.initializedControllersMap[this.controllerInitOrder[index]]==undefined){isAllInitialized=false;break;}}
if(isAllInitialized){this.controllerInitCompleted();}}
}else if(eventKey==this.events.EVENT_COOKIE_CHANGED){if(CookieUtils.getAttribute("errorCode")==this.ERROR_SESSION_TIMEOUT){
CookieUtils.deleteCookie("errorCode");}}}
var Workspace=new WorkspaceController("Workspace");
window.onload=function(){
Workspace.onLoad();}
function XmlParser(id){
this.id=id;}
XmlParser.prototype.id="XmlParser";XmlParser.prototype.usearray=true;
XmlParser.prototype.convertXmlToMap=function(xmlDocument){
var xmlArray={};
if(xmlDocument!=undefined){xmlArray[xmlDocument.nodeName]=this.parseElement(xmlDocument);}
return xmlArray;}
XmlParser.prototype.parseElement=function(element){
if(element.nodeType==7){return;}
if(element.nodeType==3||element.nodeType==4){var bool=element.nodeValue.match(/[^\x00-\x20]/);
if(bool==null){return;    }
return element.nodeValue;}
var retval;var cnt={};
if(element.attributes&&element.attributes.length){retval={};for(var i=0;i<element.attributes.length;i++){var key=element.attributes[i].nodeName;if(typeof(key)!="string"){
continue;}
var val=element.attributes[i].nodeValue;if(!val){
continue;}
if(typeof(cnt[key])=="undefined"){cnt[key]=0;}
cnt[key]++;
this.addNode(retval,key,cnt[key],val);}}
if(element.childNodes&&element.childNodes.length){var textonly=true;if(retval)textonly=false;       
for(var i=0;i<element.childNodes.length&&textonly;i++){var ntype=element.childNodes[i].nodeType;if(ntype==3||ntype==4){continue;}
textonly=false;}
if(textonly){if(!retval){
retval="";}
for(var i=0;i<element.childNodes.length;i++){retval+=element.childNodes[i].nodeValue;}}else{if(!retval){retval={};}
for(var i=0;i<element.childNodes.length;i++){
var key=element.childNodes[i].nodeName;if(typeof(key)!="string"){continue;}
var val=this.parseElement(element.childNodes[i]);if(!val){continue;}
if(typeof(cnt[key])=="undefined"){cnt[key]=0;}
cnt[key]++;
this.addNode(retval,key,cnt[key],val);}}}
return retval;};
XmlParser.prototype.addNode=function(hash,key,cnts,val){
if(this.usearray==true){             
if(cnts==1)hash[key]=[];hash[key][hash[key].length]=val;     
}else if(this.usearray==false){     
if(cnts==1)hash[key]=val;      
}else if(this.usearray==null){if(cnts==1){                     
hash[key]=val;}else if(cnts==2){              
hash[key]=[ hash[key],val ];}else{                               
hash[key][hash[key].length]=val;}
}else if(this.usearray[key]){if(cnts==1)hash[key]=[];hash[key][hash[key].length]=val;     
}else{if(cnts==1)hash[key]=val;      }};
var xmlParser=new XmlParser("xmlParser");
function DebugController(id){
this.id=id;this.init();}
DebugController.prototype.id="DebugController";DebugController.prototype.debugParseAttributes=undefined;
DebugController.prototype.init=function(){
this.debugParseAttributes={keyValueSeparator:"=<b>",pairSeparator:"</b>,<br/>",arrayOpeningSeparator:"[<br/>",arrayClosingSeparator:"</b>]<br/>",mapOpeningSeparator:"{<br/>",mapClosingSeparator:"</b>}<br/>",stringOpeningSeparator:"\"",stringClosingSeparator:"\"",isShowArrayIndex:true,isIndentByLevel:true,maxRecursionLevel:5}}
DebugController.prototype.debugMethod=function(methodName){
var functionObject=eval(methodName);var functionCodeArray=undefined;
if(functionObject!=undefined&&typeof(functionObject)=="function"){logCodeLine="breakpoint;";
functionCodeArray=functionObject.toString().split("{");functionCodeArray[1]="breakpoint;"+functionCodeArray[1];
eval(methodName+"="+functionCodeArray.join("{"));log.debug("Debug statement added to "+methodName,this);}}
DebugController.prototype.debugVariable=function(expression){
Workspace.message.displayMessage({message:ParserUtils.serializeObject(eval(expression),this.debugParseAttributes),title:"Variable Debug",messageObjectId:"debugVariable"});}
DebugController.prototype.breakpoint=function(isConditionTrue){
isConditionTrue=(isConditionTrue==undefined?true : isConditionTrue);
if(typeof(log)!="undefined"&&log.errorLevel==log.LEVEL_DEBUG&&isConditionTrue&&confirm("debug?")){breakpoint;}}
var debug=new DebugController("debug");
function LogController(pId){
this.id=pId;
if(getQuery().log!=undefined){
this.enable();
if(getQuery().log=="error"){this.errorLevel=this.LEVEL_ERROR;}else if(getQuery().log=="info"){this.errorLevel=this.LEVEL_INFO;}else if(getQuery().log=="debug"){this.errorLevel=this.LEVEL_DEBUG;}else{this.errorLevel=this.LEVEL_INFO;}}}
LogController.prototype.LEVEL_ERROR=0;LogController.prototype.LEVEL_INFO=1;LogController.prototype.LEVEL_DEBUG=2;LogController.prototype.LEVEL_TRACE=3;
LogController.prototype.id="LogController";LogController.prototype.isEnabled=false;LogController.prototype.isInitialized=false;LogController.prototype.logElement=undefined;LogController.prototype.codeEditorElement=undefined;LogController.prototype.windowHandle=undefined;LogController.prototype.containerHTML="<html><body><table border='0' style='font:courier new;font-size:11px;'>|</table></body></html>";LogController.prototype.errorLevel=LogController.LEVEL_ERROR;LogController.prototype.maxLogLineCount=20000;LogController.prototype.filterObjectIdList=new Array();LogController.prototype.editedExpression=undefined;LogController.prototype.logParserAttributes=undefined;LogController.prototype.consoleInputHistory=new Array();LogController.prototype._isDragActivated=false;LogController.prototype.currentLog="";
LogController.prototype.init=function(){
this.isInitialized=true;
Workspace.importClass("DebugController");Workspace.importClass("DragDropController");
Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);
if(this.logParserAttributes==undefined){
this.logParserAttributes={keyValueSeparator:"=",pairSeparator:",\n",arrayOpeningSeparator:"[\n",arrayClosingSeparator:"]\n",mapOpeningSeparator:"{\n",mapClosingSeparator:"}\n",stringOpeningSeparator:"\"",stringClosingSeparator:"\"",isShowArrayIndex:true,isIndentByLevel:true,maxRecursionLevel:5}}
this.showOnly(State.get(this.id+"_filterObjectIdList"));}
LogController.prototype.append=function(message,referenceObject, errorLevel){
if(this.isEnabled){
var isMessageLoggeable=true;
if(this.filterObjectIdList.length>0){isMessageLoggeable=false;
for(var index in this.filterObjectIdList){if(referenceObject==undefined||this.filterObjectIdList[index]==referenceObject.id){isMessageLoggeable=true;break;}}}
if(isMessageLoggeable&&this.errorLevel>=errorLevel){this.logToScreen(message,errorLevel,referenceObject);}}}
LogController.prototype.error=function(message,referenceObject){
if(this.isEnabled){this.append(message,referenceObject,this.LEVEL_ERROR);}}
LogController.prototype.info=function(message,referenceObject){
if(this.isEnabled){this.append(message,referenceObject,this.LEVEL_INFO);}}
LogController.prototype.debug=function(message,referenceObject){
if(this.isEnabled){this.append(message,referenceObject,this.LEVEL_DEBUG);}}
LogController.prototype.trace=function(message,referenceObject){
if(this.isEnabled){this.append(message,referenceObject,this.LEVEL_TRACE);}}
LogController.prototype.showOnly=function(objectIdList){
if(objectIdList!=undefined&&objectIdList!=""){this.filterObjectIdList=objectIdList.split(",");}else{this.filterObjectIdList=new Array();}
State.set(this.id+"_filterObjectIdList",this.filterObjectIdList.join(","));}
LogController.prototype.enable=function(){
this.isEnabled=true;}
LogController.prototype.disable=function(){
this.isEnabled=false;}
LogController.prototype.clear=function(){
this.currentLog="";
document.getElementById(this.id+"_console").value="";}
LogController.prototype.adjustConsole=function(){
var consolePanel=document.getElementById(this.id+"_console");
consolePanel.style.width=(parseInt(this.logElement.style.width)-10)+"px";consolePanel.style.height=(parseInt(this.logElement.style.height)-10-parseInt(consolePanel.style.top))+"px";}
LogController.prototype.onConsoleInput=function(e){
var value=document.getElementById(this.id+"_input").value;
this.hideHistory();
if(e.keyCode==13){
this.consoleInputHistory.push(value);
if(value.toLowerCase().indexOf("edit:")==0){
value=value.match(/.*:(.*)/)[1];
document.getElementById(this.codeEditorElement.id).style.display="block";
this.editedExpression=value;
if(typeof(eval(value))=="function"){value=eval(value).toString();}else{value=ParserUtils.serializeObject(eval(value));}
document.getElementById(this.codeEditorElement.id+"_input").value=value;document.getElementById(this.codeEditorElement.id+"_title").innerHTML=this.editedExpression;}else if(value.toLowerCase().indexOf("viewurl:")==0){
value=value.match(/.*\:(.*)/)[1];
det.sendRequest({serverUrl:value,method:"GET",responseFormat:det.RESPONSE_FORMAT_TEXT,onCompleteScript:"document.getElementById('"+this.codeEditorElement.id+"_input"+"').value=connection.response['textResponse']"});
document.getElementById(this.codeEditorElement.id+"_title").innerHTML=value;document.getElementById(this.codeEditorElement.id+"_input").value="loading";document.getElementById(this.codeEditorElement.id).style.display="block";}else if(value.toLowerCase().indexOf("debug:")==0){
log.debug(eval(value));}else if(value=="config"){
det.sendRequest({action:"rpp",serverUrl:Workspace.serverContext+"/action/rpp",callingController:this});
document.getElementById(this.codeEditorElement.id+"_title").innerHTML=value;document.getElementById(this.codeEditorElement.id+"_input").value="loading";document.getElementById(this.codeEditorElement.id).style.display="block";}else if(value.toLowerCase().indexOf("filter:")==0){
this.showOnly(value.match(/.*\:(.*)/)[1]);}else if(value.toLowerCase().indexOf("trace:")==0){
var objectNameList=value.match(/.*\:(.*)/)[1];
this.showOnly(objectNameList);
var objectArray=objectNameList.split(",");for(var index in objectArray){try{jsClass.implementsLoggeable(eval(objectArray[index]));}catch(e){log.debug("Invalid object to trace: "+objectArray[index]);}}
}else if(value.toLowerCase()=="traceall"){
var objectArray=new Array();
for(var controllerId in Workspace.controllerInitMap){try{jsClass.implementsLoggeable(eval(controllerId));}catch(e){log.debug("Invalid object to trace: "+controllerId);}}
}else if(value.toLowerCase().indexOf("profile:")==0){
var objectNameList=value.match(/.*\:(.*)/)[1];
var objectArray=objectNameList.split(",");for(var index in objectArray){try{jsClass.implementsProfiling(eval(objectArray[index]));}catch(e){log.debug("Invalid object to profile: "+objectArray[index]);}}
}else if(value=="profileall"){
for(var controllerId in Workspace.controllerInitMap){try{jsClass.implementsProfiling(eval(controllerId));}catch(e){log.debug("Invalid object to profile: "+controllerId);}}
}else if(value.toLowerCase()=="profilereport"){
Profiler.report();}else if(value=="help"){
var helpContent=
"\n--------CONSOLE COMMANDS HELP----------------------------------------------------------------------------------------------------------------------"+
"\nhelp                 -This command"+
"\nversion              -Displays build version"+
"\nedit:[expression]    -Opens an editor to change the content of a method or variable at run-time.(ex: edit:Model.rotateLeft)"+
"\nviewurl:[url]        -Opens an editor to view the content of a file or server response from the server.(ex: viewurl:/pages/product/properties.js)"+
"\nconfig               -Opens a viewer with the server configuration"+
"\nfilter:[obj1,obj2..] -Displays only log lines coming from the specified controllers.(ex: filter:Model,OnMyModel)"+
"\ntrace:[obj1,obj2..]  -Displays trace information on the specified controllers.(ex: trace:Model,OnMyModel)"+
"\ntraceall             -Displays trace information for every controllers(outputs alot!)"+
"\nprofile:[obj1,obj2..]-Runs a profiler on the specified controllers.(ex: profile:Model,OnMyModel)"+
"\nprofileall           -Runs a profiler on all controllers."+
"\nprofilereport        -Outputs the profiler report"+
"\n-----------------------------------------------------------------------------------------------------------------------------------------------------\n";
log.debug(helpContent);}else{
try{log.debug(eval(value));}catch(e){log.debug("Console Error: "+e.message);}}
}else if(e.keyCode==10){
try{value=value.match(/(([^\(\"]*))$/)[1];
var objectId=value.match(/(.*)\./)[1];var object=eval(objectId);var partialAttribute=value.match(/.*\.(.*)/)[1];
for(var attribute in object){
if(attribute.indexOf(partialAttribute)==0){document.getElementById(this.id+"_input").value+=attribute.substring(partialAttribute.length);break;}}}catch(e){log.debug("Console Error: "+e.message);}
}else if(e.keyCode==46){value=value.match(/(([^\(\"]*))$/)[1];
try{if(typeof(eval(value))=="object"){var attributes="Expression Evaluation:\n";var object=eval(value);var attributesArray=new Array();
for(attributeName in object){attributesArray[attributesArray.length]=value+"."+attributeName;}
attributesArray.sort();
log.debug(attributesArray.join("\n"));}}catch(e){}}}
LogController.prototype.showHistory=function(){
var content="";
for(var index in this.consoleInputHistory){content+="<button class='button' style='left:0px;top:"+(((this.consoleInputHistory.length-1)-index)*20)+"px;width:490px;height:20px;' onmouseover='this.className=\"buttonHighlight\"' onmouseout='this.className=\"button\"' onclick='"+this.id+".setInputFromHistory("+index+")'>"+this.consoleInputHistory[index]+"</button>";}
document.getElementById(this.historyElement.id).innerHTML=content;document.getElementById(this.historyElement.id).style.display="block";}
LogController.prototype.setInputFromHistory=function(index){
document.getElementById(this.id+"_input").value=this.consoleInputHistory[index];this.hideHistory();}
LogController.prototype.hideHistory=function(){
document.getElementById(this.historyElement.id).style.display="none";}
LogController.prototype.editExpression=function(){
eval(this.editedExpression+"="+document.getElementById(this.codeEditorElement.id+"_input").value);}
LogController.prototype.logToScreen=function(logLine,errorLevel,pReferenceObject){
if(this.currentLog.length>this.maxLogLineCount){this.currentLog=this.currentLog.substring(0,this.maxLogLineCount)+"\r\n...";}
if(typeof(logLine)!="string"){logLine=ParserUtils.serializeObject(logLine,this.logParserAttributes);}
var rightNow=new Date();
if(errorLevel==this.LEVEL_ERROR){
logLine="\r\n********************************************************************************************************\r\n"+
" ERROR:"+(pReferenceObject!=undefined&&pReferenceObject.id!=undefined?"("+pReferenceObject.id+")" : "")+
logLine+"\r\n"+
"********************************************************************************************************\r\n\r\n";}else{logLine=rightNow.getHours()+":"+rightNow.getMinutes()+":"+rightNow.getSeconds()+":"+rightNow.getMilliseconds()+"\t"+(pReferenceObject!=undefined&&pReferenceObject.id!=undefined?"("+pReferenceObject.id+")" : "")+
logLine+"\r\n";}
this.currentLog=logLine+this.currentLog;
if(Workspace.isInitialized&&!this.isInitialized){this.init();}else{
if(this.logElement==undefined&&document.body!=undefined){
this.logElement=document.createElement("div");this.logElement.id=this.id+"_panel";this.logElement.className="panel";this.logElement.style.position="absolute";this.logElement.style.width="910px";this.logElement.style.height="300px";this.logElement.style.left="0px";this.logElement.style.top="520px";this.logElement.setAttribute("tLeft",0);this.logElement.setAttribute("tTop",0);this.logElement.setAttribute("tWidth",parseInt(document.body.clientWidth));this.logElement.setAttribute("tHeight",parseInt((document.body.clientHeight>0?document.body.clientHeight : document.documentElement.clientHeight)));this.logElement.setAttribute("onOpen",this.id+".adjustConsole()");this.logElement.setAttribute("onClose",this.id+".adjustConsole()");
document.body.appendChild(this.logElement);
this.logElement.innerHTML=
"<div id='"+this.id+"_consoleTitleBar' class='label' style='left:30px;top:3px;width:880px;height:30px;cursor:pointer;' onDblClick='Anim.openAndClose(\""+this.id+"_panel\")'>Console</div>"+
"<button style='position:absolute;left:2px;top:2px;width:20px;height:20px;' onclick='Anim.openAndClose(\""+this.id+"_panel\")' class='button'>+</button>"+
"<input id='"+this.id+"_input' "+
"style='position:absolute;left:5px;top:30px;width:900px;height:20px;background-color:black;border:0px;color:white;font-weight:bold;' class='transparent70'"+
"onkeypress='"+this.id+".onConsoleInput((window.event!=undefined?window.event : event))' "+
">"+
"<textarea id='"+this.id+"_console' "+
"style='position:absolute;left:5px;top:52px;width:900px;height:245px;' wrap='off'>"+
"</textarea>"+
"<button style='position:absolute;left:810px;top:30px;width:50px;height:20px;' class='button' onmouseover='this.className=\"buttonHighlight\"' onmouseout='this.className=\"button\"' onclick='"+this.id+".showHistory()'>History</button>"+
"<button style='position:absolute;left:860px;top:30px;width:50px;height:20px;' class='button' onmouseover='this.className=\"buttonHighlight\"' onmouseout='this.className=\"button\"' onclick='"+this.id+".clear()'>Clear</button>";
this.codeEditorElement=document.createElement("div");this.codeEditorElement.id=this.id+"_codeEditor";this.codeEditorElement.style.position="absolute";this.codeEditorElement.style.width="610px";this.codeEditorElement.style.height="300px";this.codeEditorElement.style.left="50%";this.codeEditorElement.style.top="50%";this.codeEditorElement.style.marginRight=parseInt(this.codeEditorElement.style.width)/2+"px";this.codeEditorElement.style.marginBottom=parseInt(this.codeEditorElement.style.height)/2+"px";this.codeEditorElement.style.display="none";this.codeEditorElement.setAttribute("tLeft",0);this.codeEditorElement.setAttribute("tTop",0);this.codeEditorElement.setAttribute("tWidth",parseInt(document.body.clientWidth));this.codeEditorElement.setAttribute("tHeight",parseInt((document.body.clientHeight>0?document.body.clientHeight : document.documentElement.clientHeight)));
this.codeEditorElement.innerHTML=
"<div style='position:absolute;left:0px;top:0px;width:100%;height:100%;background-color:white;font-family:arial;font-size:11px;font-weight:bold;color:#04438F;border:1px solid #A9C1DB;background-color:white;filter:alpha(opacity:90);KHTMLOpacity:0.9;MozOpacity:0.9;opacity:0.9;' class='panel'>"+
"<button style='position:absolute;left:2px;top:2px;width:20px;height:20px;' onClick='Anim.openAndClose(\""+this.codeEditorElement.id+"\")' class='button'>+</button>"+
"<div id='"+this.codeEditorElement.id+"_title' style='position:absolute;left:30px;top:3px;width:100%;height:20;cursor:pointer;' onDblClick='Anim.openAndClose(\""+this.codeEditorElement.id+"\")' class='label'></div>"+
"<textarea id='"+this.codeEditorElement.id+"_input' "+
"style='position:absolute;left:5px;top:25px;width:99%;height:90%;font-size:11px;background-color:#000000;color:#FFFFFF;' wrap='off'>"+
"</textarea>"+
"<button style='position:absolute;left:673px;top:0px;width:60px;height:20px;' class='button' onmouseover='this.className=\"buttonHighlight\"' onmouseout='this.className=\"button\"' onclick='document.getElementById(\""+this.codeEditorElement.id+"\").style.display=\"none\";'>cancel</button>"+
"<button style='position:absolute;left:735px;top:0px;width:60px;height:20px;' class='button' onmouseover='this.className=\"buttonHighlight\"' onmouseout='this.className=\"button\"' onclick='"+this.id+".editExpression();document.getElementById(\""+this.codeEditorElement.id+"\").style.display=\"none\";'>save</button>"+
"</div>";
document.body.appendChild(this.codeEditorElement);
this.historyElement=document.createElement("div");this.historyElement.id=this.id+"_history";this.historyElement.style.position="absolute";this.historyElement.style.left="0px";this.historyElement.style.top="50px";this.historyElement.style.width="100%";this.historyElement.style.height="400px";this.historyElement.style.display="none";
this.logElement.appendChild(this.historyElement);}
if(!this._isDragActivated&&typeof(DragDrop)!="undefined"&&document.getElementById(this.id+"_consoleTitleBar")!=undefined){
this._isDragActivated=true;DragDrop.doDrag(this.id+"_consoleTitleBar",{"draggedElementId":this.logElement.id});DragDrop.doDrag(this.codeEditorElement.id+"_title",{"draggedElementId":this.codeEditorElement.id});}
document.getElementById(this.id+"_console").value=this.currentLog;}}
LogController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED){
if(attributes.action=="rpp"){document.getElementById(this.codeEditorElement.id+"_input").value=ParserUtils.serializeObject(attributes.response,this.logParserAttributes);}}}
var log=new LogController("log");
function ProfilerController(id){
this.id=id;}
ProfilerController.prototype.id="ProfilerController";ProfilerController.prototype.logArray=new Array();
ProfilerController.prototype.reset=function(){
this.logArray=new Array();}
ProfilerController.prototype.methodIn=function(methodName){
this.logArray.push({id:methodName,type:"in",time:new Date().getTime()});}
ProfilerController.prototype.methodOut=function(methodName){
this.logArray.push({id:methodName,type:"out",time:new Date().getTime()});}
ProfilerController.prototype.report=function(){
var methodCallCountMap=new Array();var methodTimeMap=new Array();var methodCallTree=new Array();
var methodTimeMapBuilder=new Array();
var cursor=methodCallTree;
var logLine=undefined;
for(var index in this.logArray){
logLine=this.logArray[index];
if(logLine["type"]=="in"){
if(methodCallCountMap[logLine["id"]]==undefined){methodCallCountMap[logLine["id"]]=0;}
methodCallCountMap[logLine["id"]]++;
if(methodTimeMapBuilder[logLine["id"]]==undefined){methodTimeMapBuilder[logLine["id"]]=new Array();}
methodTimeMapBuilder[logLine["id"]].push(logLine["time"]);}else if(logLine["type"]=="out"){
if(methodTimeMap[logLine["id"]]==undefined){methodTimeMap[logLine["id"]]=0;}
methodTimeMap[logLine["id"]]+=(logLine["time"]-methodTimeMapBuilder[logLine["id"]].pop());}}
for(var methodName in methodCallCountMap){
log.debug(methodName+"\t\t\t\tcount:"+methodCallCountMap[methodName]+"\t\ttime:"+methodTimeMap[methodName]);}}
var Profiler=new ProfilerController("profiler");
function UnitTestController(id){
this.id=id;this._init();}
UnitTestController.prototype.id="UnitTestController";UnitTestController.prototype.eventList=undefined;UnitTestController.prototype.eventIndex=0;UnitTestController.prototype.startTime=undefined;UnitTestController.prototype.isRecording=false;UnitTestController.prototype.overlayHighlightElement=undefined;UnitTestController.prototype.window=undefined;UnitTestController.prototype.filePath="";UnitTestController.prototype.autoRunScriptName="";UnitTestController.prototype.speedAdjust=2;
UnitTestController.prototype._init=function(){
this.filePath=Workspace.skinPath+"/test/";
resource.applyProperties(this.id+"Properties",this);
document.onclick=function(){UnitTest._recordEvent(event);};
document.onmousedown=function(){UnitTest._recordEvent(event);};
document.onmouseup=function(){UnitTest._recordEvent(event);};
document.onkeyup=function(){UnitTest._recordEvent(event);};
Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);Workspace.events.addListener(Workspace.events.EVENT_PAGE_LOADED,this);
this.window=new WindowController(this.id+".window",{"templateId":this.id+"Template","controller":this.id,"title":"Unit Test Control Panel","autoShow":true,"left":910,"top":500,"width":500,"height":300});
this.eventList=new Array();this.eventIndex=0;
this._generate();
if(Workspace.query.runtest!=undefined&&Workspace.query.runtest!=""){this.autoRunScriptName=Workspace.query.runtest;}}
UnitTestController.prototype._generate=function(){
this.overlayHighlightElement=document.createElement("div");this.overlayHighlightElement.id=this.id+"OverlayHighlightElement";this.overlayHighlightElement.style.position="absolute";this.overlayHighlightElement.innerHTML="<span style='font-size:20px;font-family:Wingdings'>�</span><span id='"+this.id+"Status'></span>";
document.body.appendChild(this.overlayHighlightElement);}
UnitTestController.prototype.loadScript=function(scriptName){
det.sendRequest({method:"GET",responseFormat:det.RESPONSE_FORMAT_TEXT,serverUrl:this.filePath+scriptName+".js",action:"getScript",callingController:this});}
UnitTestController.prototype.startRecord=function(){
this.eventList=new Array();this.startTime=new Date().getTime();
this.isRecording=true;this.overlayHighlightElement.style.display="none";
if(typeof(log.showOnly)!="undefined"){log.showOnly(this.id);}
this.window.generate();}
UnitTestController.prototype.stopRecord=function(){
this.isRecording=false;this.window.generate();}
/**
* Returns the element DOM path(hierarchical position of the element)
* @param{HTMLElement}HTML element to get the dom path from
* @return Stringex:"/0/3/1/2"
*/
UnitTestController.prototype._getDomPath=function(element){
var xpath="";
while(element!=document.body){
for(var i=0;i<element.parentNode.childNodes.length;i++){if(element==element.parentNode.childNodes[i]){xpath="/"+i+xpath;break;}}
element=element.parentNode;}
return xpath;}
/**
* Returns an element from its DOM path
* @param{String}DOM path(ex: /0/2/3/4)
* @return HTMLElementHTML Element that matches the DOM path
*/
UnitTestController.prototype._getElementFromDomPath=function(domPath){
var node=document.body;var level=1;
var domArray=domPath.split("/");
while(node.childNodes[parseInt(domArray[level])]!=undefined){node=node.childNodes[parseInt(domArray[level])];level++;}
if(level==domArray.length){return node;}else{return undefined;}}
UnitTestController.prototype._recordEvent=function(event){
if(this.isRecording&&event.srcElement!=undefined&&event.srcElement.id.indexOf("UnitTest")==-1){
var previousElement=(this.eventList.length>0?this._getElementFromDomPath(this.eventList[this.eventList.length-1]["elementPath"]): undefined);var elementDomPath=this._getDomPath(event.srcElement);
if(event.type=="click"||(event.type=="mousedown"&&event.srcElement.tagName.toLowerCase()=="button")){
if(previousElement!=undefined&&(previousElement.tagName.toLowerCase()=="input"||previousElement.tagName.toLowerCase()=="textarea")){this.eventList.push({"event":"blur","elementPath":this.eventList[this.eventList.length-1]["elementPath"],"timestamp":new Date().getTime()-this.startTime,"x":this.eventList[this.eventList.length-1]["x"],"y":this.eventList[this.eventList.length-1]["y"]});log.debug("+blur->"+this.eventList[this.eventList.length-1]["elementPath"],this);
}else if(previousElement!=undefined&&previousElement.tagName.toLowerCase()=="select"){this.eventList.push({"event":"setInputValue","elementPath":this.eventList[this.eventList.length-1]["elementPath"],"timestamp":new Date().getTime()-this.startTime,"value":previousElement.value,"x":this.eventList[this.eventList.length-1]["x"],"y":this.eventList[this.eventList.length-1]["y"]});log.debug("testRecord:+select->"+this.eventList[this.eventList.length-1]["elementPath"]+"="+previousElement.value,this);}
if(event.srcElement.tagName.toLowerCase()=="input"||event.srcElement.tagName.toLowerCase()=="textarea"){this.eventList.push({"event":"focus","elementPath":elementDomPath,"timestamp":new Date().getTime()-this.startTime,"x":event.x,"y":event.y});log.debug("+focus->"+elementDomPath,this);}
this.eventList.push({"event":"click","elementPath":elementDomPath,"timestamp":new Date().getTime()-this.startTime,"x":event.x,"y":event.y});log.debug("testRecord:+click->"+elementDomPath,this);}else if(event.type=="keyup"&&(event.srcElement.tagName.toLowerCase()=="input"||event.srcElement.tagName.toLowerCase()=="textarea")){
this.eventList.push({"event":"setInputValue","elementPath":elementDomPath,"value":event.srcElement.value,"timestamp":new Date().getTime()-this.startTime,"x":event.x,"y":event.y});log.debug("testRecord:+keyup->"+elementDomPath,this);}else{log.debug("Did not record "+event.type+" on elementID: "+elementDomPath+"-"+event.srcElement.tagName,this);}}}
UnitTestController.prototype.replay=function(){
this.overlayHighlightElement.style.display="block";this.eventIndex=0;this._replayNext();}
UnitTestController.prototype._replayNext=function(){
var event=this.eventList[this.eventIndex];var previousEvent=undefined;var nextEvent=undefined;
if(this.eventIndex>0){var previousEvent=this.eventList[this.eventIndex-1];}
if(this.eventIndex<this.eventList.length-1){var nextEvent=this.eventList[this.eventIndex+1];
var nextEventElement=this._getElementFromDomPath(nextEvent["elementPath"]);
if(nextEventElement!=undefined){var attributes=new Array();attributes["tLeft"]=getAbsLeft(nextEventElement)+(getWidth(nextEventElement)/2);attributes["tTop"]=getAbsTop(nextEventElement)+(getHeight(nextEventElement)/2);attributes["duration"]=200;Anim.animateElement(this.overlayHighlightElement.id,attributes);}}
document.getElementById(this.id+"Status").innerHTML=event["event"];
if(event["event"]=="setInputValue"){this._replayElementSetValue(event);}else if(event["event"]=="focus"){this._replayElementFocus(event);}else if(event["event"]=="blur"){this._replayElementBlur(event);}else{this._replayElementOnEvent(event);}
if(this.eventIndex<this.eventList.length-1){this.eventIndex++;setTimeout(this.id+"._replayNext()",(event["timestamp"]-(previousEvent!=undefined?previousEvent["timestamp"] : 0))*2);}}
UnitTestController.prototype._replayElementSetValue=function(event){
var element=this._getElementFromDomPath(event["elementPath"]);if(element!=undefined){log.debug("setting element "+element.id+"("+event["elementPath"]+")"+" value to: "+event["value"],this);element.value=event["value"];}else{throw("Unit Test Error: Element could not be found("+event["elementPath"]+")");}}
UnitTestController.prototype._replayElementFocus=function(event){
var element=this._getElementFromDomPath(event["elementPath"]);if(element!=undefined){log.debug("setting focus on element "+element.id+"("+event["elementPath"]+")",this);element.focus();}else{throw("Unit Test Error: Element could not be found("+event["elementPath"]+")");}}
UnitTestController.prototype._replayElementBlur=function(event){
var element=this._getElementFromDomPath(event["elementPath"]);if(element!=undefined){log.debug("setting blur on element "+element.id+"("+event["elementPath"]+")",this);element.onblur();}else{throw("Unit Test Error: Element could not be found("+event["elementPath"]+")");}}
UnitTestController.prototype._replayElementOnEvent=function(event){
var element=this._getElementFromDomPath(event["elementPath"]);if(element!=undefined){if(event["event"]=="click"){log.debug("calling "+event["event"]+" on element "+element.id+"("+event["elementPath"]+")",this);element.click();}}else{throw("Unit Test Error: Element could not be found("+event["elementPath"]+")");}}
UnitTestController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED&&attributes!=undefined&&attributes.response!=undefined){
log.debug(attributes.action+": "+(attributes.timeReceived.getTime()-attributes.timeSent.getTime())/1000+"s",this);
if(attributes.response["errorCode"]!=undefined){throw("Server error detected while running unit tests: "+attributes.response["errorCode"])}
if(attributes.callingController==this&&attributes.action=="getScript"){
this.eventList=eval(attributes.response["textResponse"]);this.replay();}
}else if(eventKey==Workspace.events.EVENT_PAGE_LOADED){
if(this.autoRunScriptName!=""){this.loadScript(this.autoRunScriptName);}}}
function getAbsLeft(pObject){var pObject_Left=pObject.offsetLeft;while(pObject.offsetParent!=null){pObject_Left+=(pObject.offsetParent.offsetLeft-pObject.offsetParent.scrollLeft);pObject=pObject.offsetParent;}
var windowScrollLeft=0
if(typeof(window.pageYOffset)=='number'){windowScrollLeft=window.pageXOffset;}else if(document.body&&(document.body.scrollLeft||document.body.scrollTop)){windowScrollLeft=document.body.scrollLeft;}else if(document.documentElement&&(document.documentElement.scrollLeft||document.documentElement.scrollTop)){windowScrollLeft=document.documentElement.scrollLeft;}
return pObject_Left+windowScrollLeft;}
function getAbsTop(pObject){var pObject_Top=pObject.offsetTop;while(pObject.offsetParent!=null){pObject_Top+=(pObject.offsetParent.offsetTop-pObject.offsetParent.scrollTop);pObject=pObject.offsetParent;}
var windowScrollTop=0;if(typeof(window.pageYOffset)=='number'){windowScrollTop=window.pageYOffset;}else if(document.body&&(document.body.scrollLeft||document.body.scrollTop)){windowScrollTop=document.body.scrollTop;}else if(document.documentElement&&(document.documentElement.scrollLeft||document.documentElement.scrollTop)){windowScrollTop=document.documentElement.scrollTop;}
return pObject_Top+windowScrollTop;}
function getLeft(pObject){return parseInt(pObject.offsetLeft);}
function getTop(pObject){return parseInt(pObject.offsetTop);}
function getWidth(pObject){var returnValue=0;
if(pObject!=0&&pObject!=undefined){if(pObject.clientWidth!=undefined&&pObject.clientWidth!=0){returnValue=parseInt(pObject.clientWidth);}
else if(pObject.style.width&&pObject.style.width!=""&&pObject.style.width!=0){returnValue=parseInt(pObject.style.width);}
else if(pObject.offsetWidth&&pObject.offsetWidth!=0){returnValue=parseInt(pObject.offsetWidth);}}
return returnValue;}
function getHeight(pObject){var returnValue=0;
if(pObject!=0&&pObject!=undefined){if(pObject.clientHeight!=undefined&&pObject.clientHeight!=0){returnValue=parseInt(pObject.clientHeight);}
else if(pObject.style.height&&pObject.style.height!=""&&pObject.style.height!=0){returnValue=parseInt(pObject.style.height);}
else if(pObject.offsetHeight&&pObject.offsetHeight!=0){returnValue=parseInt(pObject.offsetHeight);}}
return returnValue;}
function setLeft(pObject,pLeft){if(pObject!=0&&pObject!=undefined){pObject.style.left=pLeft+"px";}}
function setTop(pObject,pTop){if(pObject!=0&&pObject!=undefined){pObject.style.top=pTop+"px";}}
function setAbsLeft(pObject,pLeft){if(pObject!=0&&pObject!=undefined){pObject.style.pixelLeft=pLeft+"px";}}
function setAbsTop(pObject,pTop){if(pObject!=0&&pObject!=undefined){pObject.style.pixelTop=pTop+"px";}}
function setWidth(pObject,pWidth){if(pObject!=0&&pObject!=undefined){pObject.style.width=(pWidth>-1?pWidth:0)+"px";}}
function setHeight(pObject,pHeight){if(pObject!=0&&pObject!=undefined){pObject.style.height=(pHeight>-1?pHeight:0)+"px";}}
function getWindowWidth(){return document.body.clientWidth-5;}
function getWindowHeight(){return document.documentElement.clientHeight-5;}
function isDefined(pObject){return(pObject!=undefined&&pObject!=0&&pObject!=""?true : false);}
function setErrorImage(pImgElement,pImagePath){
var currentSrc=pImgElement.src;
var indexInCurrentSrc=currentSrc.lastIndexOf(pImagePath);var differentEnd=((pImagePath.length<=currentSrc.length)&&(indexInCurrentSrc==-1||indexInCurrentSrc!=(currentSrc.length-pImagePath.length)));
if(differentEnd){pImgElement.src=pImagePath;}}
function getElementBoundingBox(element){
return new Array(
getAbsLeft(element),getAbsTop(element),getAbsLeft(element)+getWidth(element),getAbsTop(element)+getHeight(element))}
function addItemToList(pArray,pSelectElement){
pSelectElement.options[pSelectElement.options.length]=new Option(pArray[0],pArray[1]);}
function getElementColumns(itemElementWidth,containerElement){
var columns=1;
if(containerElement!=undefined){var containerWidth=parseInt(containerElement.style.width);
columns=Math.floor(itemElementWidth/containerWidth);}
return columns;}
function getE(elementId){return document.getElementById(elementId);}
function getMouseState(pEvent){
var pX=0;
var  pY=0;
var mouseState=new Object();mouseState.left=0;mouseState.top=0;mouseState.button=0;
var windowScrollTop=0;if(typeof(window.pageYOffset)=='number'){windowScrollTop=window.pageYOffset;}else if(document.body&&(document.body.scrollLeft||document.body.scrollTop)){windowScrollTop=document.body.scrollTop;}else if(document.documentElement&&(document.documentElement.scrollLeft||document.documentElement.scrollTop)){windowScrollTop=document.documentElement.scrollTop;}
var windowScrollLeft=0
if(typeof(window.pageYOffset)=='number'){windowScrollLeft=window.pageXOffset;}else if(document.body&&(document.body.scrollLeft||document.body.scrollTop)){windowScrollLeft=document.body.scrollLeft;}else if(document.documentElement&&(document.documentElement.scrollLeft||document.documentElement.scrollTop)){windowScrollLeft=document.documentElement.scrollLeft;}
if(pEvent.pageX!=undefined){mouseState.left=pEvent.pageX+windowScrollLeft;mouseState.top=pEvent.pageY+windowScrollTop;}else{mouseState.left=pEvent.clientX+windowScrollLeft;mouseState.top=pEvent.clientY+windowScrollTop;}
if(parseInt(navigator.appVersion)>3){if(navigator.appName=="Netscape"){mouseState.button=pEvent.which;}else{mouseState.button=pEvent.button;}}
return mouseState;}
function loopUntil(condition,onComplete,frequency,loopCount){
frequency=(frequency!=undefined?frequency : 500);loopCount=(loopCount!=undefined?loopCount : 0);
if(loopCount>100){
log.error("loopUntil timeout when trying to run: "+condition);}else{
var isConditionMet=false;
try{if(eval(condition)==true){isConditionMet=true;}}catch(e){}
if(isConditionMet){eval(unescape(onComplete));}else{setTimeout("loopUntil(\""+condition+"\",\""+onComplete+"\","+frequency+","+(loopCount++)+")",frequency);}}}
function FieldObject(){}
FieldObject.prototype.FIELD_VALID=0;FieldObject.prototype.FIELD_ERROR_REQUIRED=100;FieldObject.prototype.FIELD_ERROR_INVALID_RANGE=101;FieldObject.prototype.FIELD_ERROR_INVALID_CHARACTERS=102;FieldObject.prototype.FIELD_ERROR_INVALID_EMAIL=103;FieldObject.prototype.FIELD_ERROR_INVALID_LENGTH=104;FieldObject.prototype.FIELD_ERROR_INVALID_NUMERIC=105;FieldObject.prototype.FIELD_ERROR_PASSWORD_DONT_MATCH=106;FieldObject.prototype.FIELD_ERROR_BUST_OR_BRA_REQUIRED=107;FieldObject.prototype.FIELD_DEPENDENCY_NOT_FILLED=108;
FieldObject.prototype.id="FieldObject";FieldObject.prototype.name="";FieldObject.prototype.elementId="";FieldObjectText.prototype.fieldDOMId="";FieldObject.prototype.state=0;FieldObject.prototype.initialValue="";FieldObject.prototype.value="";FieldObject.prototype.normalClass="";FieldObject.prototype.errorClass="";FieldObject.prototype.referenceController=undefined;FieldObject.prototype.isFieldChanged=false;FieldObject.prototype.isRequired=true;FieldObject.prototype.isEnabled=true;FieldObject.prototype.filledFieldDependency="";FieldObject.prototype.htmlContent="";
FieldObject.prototype.init=function(referenceController){
this.referenceController=referenceController;
var element=document.getElementById(this.elementId);
if(element!=undefined){this.getConfigFromElement(element);}else{log.error("element '"+this.elementId+"' was not found for field '"+this.id+"'",this);}}
FieldObject.prototype.getConfigFromElement=function(element){
this.name=(element.getAttribute("name")!=undefined?element.getAttribute("name"): this.elementId);this.initialValue=(element.getAttribute("value")!=undefined?element.getAttribute("value"): this.value);this.value=(element.getAttribute("value")!=undefined?element.getAttribute("value"): this.value);this.normalClass=(element.getAttribute("normalClass")!=undefined?element.getAttribute("normalClass"): this.normalClass);this.errorClass=(element.getAttribute("errorClass")!=undefined?element.getAttribute("errorClass"): this.errorClass);this.state=(element.getAttribute("state")!=undefined?element.getAttribute("state"): this.state);this.isRequired=(element.getAttribute("required")!=undefined?(element.getAttribute("required")=="false"?false : true): this.isRequired);this.isEnabled=(element.getAttribute("enabled")!=undefined?(element.getAttribute("enabled")=="false"?false : true): this.isEnabled);
this.filledFieldDependency=(element.getAttribute("filledFieldDependency")!=undefined?element.getAttribute("filledFieldDependency"): this.filledFieldDependency);}
FieldObject.prototype.generate=function(isForced){
isForced=(isForced!=undefined?isForced : false);
var element=document.getElementById(this.elementId);
if(element!=undefined){
if(this.isGenerated()){
this._updateAttributes();}else{
element.innerHTML=this.getFieldHTML();}}}
FieldObject.prototype._updateAttributes=function(){}
FieldObject.prototype.isGenerated=function(){return false;}
FieldObject.prototype.initFieldsList=function(fieldAnswers,referenceController,questionPrefix){
var fieldElement=undefined;var fieldElementId=undefined;var fieldType=undefined;
var fieldObjectMap=new Array();
for(var fieldId in fieldAnswers){
fieldElementId=questionPrefix+"_"+fieldId;fieldElement=document.getElementById(fieldElementId);
if(fieldElement!=undefined){
fieldType=(fieldElement.getAttribute("fieldType")!=undefined?fieldElement.getAttribute("fieldType"): "text");
if(fieldType=="text"){fieldObjectMap[fieldId]=new FieldObjectText(referenceController.id+".fieldObjectMap['"+fieldId+"']",fieldElementId);}else if(fieldType=="numeric"){fieldObjectMap[fieldId]=new FieldObjectNumeric(referenceController.id+".fieldObjectMap['"+fieldId+"']",fieldElementId);}else if(fieldType=="weight"){fieldObjectMap[fieldId]=new FieldObjectWeight(referenceController.id+".fieldObjectMap['"+fieldId+"']",fieldElementId);}else if(fieldType=="height"){fieldObjectMap[fieldId]=new FieldObjectHeight(referenceController.id+".fieldObjectMap['"+fieldId+"']",fieldElementId);}else if(fieldType=="imageList"){fieldObjectMap[fieldId]=new FieldObjectImageList(referenceController.id+".fieldObjectMap['"+fieldId+"']",fieldElementId);}else if(fieldType=="combo"){fieldObjectMap[fieldId]=new FieldObjectCombo(referenceController.id+".fieldObjectMap['"+fieldId+"']",fieldElementId);}else if(fieldType=="email"){fieldObjectMap[fieldId]=new FieldObjectEmail(referenceController.id+".fieldObjectMap['"+fieldId+"']",fieldElementId);}else if(fieldType=="year"){fieldObjectMap[fieldId]=new FieldObjectYear(referenceController.id+".fieldObjectMap['"+fieldId+"']",fieldElementId);}else if(fieldType=="checkbox"){fieldObjectMap[fieldId]=new FieldObjectCheckbox(referenceController.id+".fieldObjectMap['"+fieldId+"']",fieldElementId);}else if(fieldType=="password"){fieldObjectMap[fieldId]=new FieldObjectPassword(referenceController.id+".fieldObjectMap['"+fieldId+"']",fieldElementId);}
if(fieldObjectMap[fieldId]!=undefined){
fieldObjectMap[fieldId].init(referenceController);
if(fieldAnswers!=undefined){fieldObjectMap[fieldId].setInitialValue(fieldAnswers[fieldId]);}
fieldObjectMap[fieldId].generate();}}else{log.info("WARNING: "+referenceController.id+"'s Field ["+fieldElementId+"] definition in template not found",this);}}
return fieldObjectMap;}
FieldObject.prototype.isAllFieldsValid=function(fieldObjectMap){
var result=true;
if(fieldObjectMap==undefined){result=false;}else{for(var fieldName in fieldObjectMap){
fieldObjectMap[fieldName].state=fieldObjectMap[fieldName].isValid();
if(fieldObjectMap[fieldName].state!=this.FIELD_VALID){result=false;}}}
return result;}
FieldObject.prototype.updateFields=function(fieldObjectMap){
for(var fieldName in fieldObjectMap){this.updateField(fieldObjectMap[fieldName]);}}
FieldObject.prototype.updateField=function(fieldObject){
fieldObject.isFieldChanged=true;fieldObject.state=fieldObject.isValid();fieldObject.generate();}
FieldObject.prototype.setInitialValue=function(value){
value=value+"";
this.initialValue=value;this.isFieldChanged=false;this.value=value;}
FieldObject.prototype.setValue=function(value,isForced){(isForced!=undefined?isForced : false);
value=value+"";
if(this.value!=value){
this.value=value;
var newState=this.isValid();
this.state=newState
this.generate(isForced);
this.onFieldChange();}}
FieldObject.prototype.getValue=function(){
return encodeToUnicode(this.value);}
FieldObject.prototype.isChanged=function(){
return(this.isFieldChanged||this.value!=this.initialValue);}
FieldObject.prototype.parseTokens=function(text){
var stringArray=new Array;var finalString="";
stringArray=text.split("|");
for(var i=0;i<stringArray.length;i++){if(stringArray[i].indexOf("[")==0){stringArray[i]=eval("this."+stringArray[i].substring(1,stringArray[i].length-1));}
finalString+=stringArray[i];}
return finalString;}
FieldObject.prototype.onFieldChange=function(){
if(this.referenceController!=undefined&&this.referenceController.onFieldChange!=undefined){this.referenceController.onFieldChange(this);}}
FieldObject.prototype.onFieldFocus=function(){
if(this.referenceController!=undefined&&this.referenceController.onFieldFocus!=undefined){this.referenceController.onFieldFocus(this);}}
FieldObject.prototype.onFieldBlur=function(){
this.updateField(this);
if(this.referenceController!=undefined&&this.referenceController.onFieldBlur!=undefined){this.referenceController.onFieldBlur(this);}}
FieldObject.prototype.focus=function(){
var fieldElement=document.getElementById(this.name+"_field");
if(fieldElement!=undefined){fieldElement.focus();}}
FieldObject.prototype.setAllFieldsUnitSystem=function(fieldObjectMap,unitSystem,referenceController){
for(var fieldId in fieldObjectMap){fieldObjectMap[fieldId].setUnitSystem(unitSystem);}}
FieldObject.prototype.getAllFieldsAnswersMap=function(fieldObjectMap){
var map=new Array();
for(var fieldId in fieldObjectMap){map[fieldObjectMap[fieldId].name]=fieldObjectMap[fieldId].getValue();}
return map;}
FieldObject.prototype.setAllFieldsAnswers=function(fieldObjectMap,dataMap){
for(var fieldId in fieldObjectMap){
if(dataMap[fieldObjectMap[fieldId].name]!=undefined){fieldObjectMap[fieldId].setInitialValue(dataMap[fieldObjectMap[fieldId].name]);fieldObjectMap[fieldId].generate();}}}
FieldObject.prototype.setAllFieldsUnchanged=function(fieldObjectMap){
for(var fieldId in fieldObjectMap){fieldObjectMap[fieldId].isFieldChanged=false;}}
FieldObject.prototype.getFieldAttributesMap=function(){
var newMap=new Array();
for(var attribute in this){
if(typeof(this[attribute])=="string"||typeof(this[attribute])=="number"){newMap[attribute]=this[attribute];}}
return newMap;}
FieldObject.prototype.getErrorMessage=function(){
var errorMessage="";var state=this.state;
if(state==this.FIELD_ERROR_REQUIRED){errorMessage=resource.get("Questionnaire.ErrorMessage.Required");}else if(state==this.FIELD_ERROR_INVALID_CHARACTERS){errorMessage=resource.get("Questionnaire.ErrorMessage.InvalidCharacters");}else if(state==this.FIELD_ERROR_INVALID_EMAIL){errorMessage=resource.get("Questionnaire.ErrorMessage.InvalidEmail");}else if(state==this.FIELD_ERROR_INVALID_NUMERIC){errorMessage=resource.get("Questionnaire.ErrorMessage.InvalidNumeric");}else if(state==this.FIELD_ERROR_INVALID_RANGE){if(this.minValue>-1&&this.maxValue>-1){errorMessage=resource.get("Questionnaire.ErrorMessage.InvalidRange");}else if(this.minValue>-1&&this.maxValue==-1){errorMessage=resource.get("Questionnaire.ErrorMessage.InvalidMinRange");}else if(this.minValue==-1&&this.maxValue>-1){errorMessage=resource.get("Questionnaire.ErrorMessage.InvalidMaxRange");}}else if(state==this.FIELD_ERROR_PASSWORD_DONT_MATCH){errorMessage=resource.get("Questionnaire.ErrorMessage.PasswordDontMatch");}else if(state==this.FIELD_ERROR_BUST_OR_BRA_REQUIRED){errorMessage=resource.get("Questionnaire.ErrorMessage.BustOrBraRequired");}else if(state==this.FIELD_ERROR_INVALID_LENGTH){if(this.minLength>-1&&this.maxLength>-1){errorMessage=resource.get("Questionnaire.ErrorMessage.InvalidLength");}else if(this.minLength>-1&&this.maxLength==-1){errorMessage=resource.get("Questionnaire.ErrorMessage.InvalidMinLength");}else if(this.minLength==-1&&this.maxLength>-1){errorMessage=resource.get("Questionnaire.ErrorMessage.InvalidMaxLength");}else if(this.minLength==-1&&this.maxLength==-1){errorMessage=resource.get("Questionnaire.ErrorMessage.Required");}}else if(state==this.FIELD_DEPENDENCY_NOT_FILLED){errorMessage=resource.get("Questionnaire.ErrorMessage.BustOrBraRequired");}
errorMessage=ParserUtils.parseHtml(errorMessage,this.getFieldAttributesMap());
return errorMessage;}
FieldObject.prototype.enable=function(){
this.isEnabled=true;this.generate();}
FieldObject.prototype.disable=function(){
this.isEnabled=false;this.generate();}
FieldObject.prototype.getFieldHTML=function(){return "";}
FieldObject.prototype.isValid=function(){
var fieldValid=this.FIELD_VALID;
if(this.referenceController!=undefined&&this.referenceController.fieldObjectMap!=undefined&&this.filledFieldDependency!=""&&this.value==""&&this.referenceController.fieldObjectMap[this.filledFieldDependency].getValue()==""){
fieldValid=this.FIELD_DEPENDENCY_NOT_FILLED;}
return fieldValid;}
FieldObject.prototype.setUnitSystem=function(unitSystem){}
var FieldUtils=new FieldObject();
function FieldObjectCheckbox(id,elementId){jsClass.extend(this,[FieldObject]);
this.id=id;this.elementId=elementId;}
FieldObjectCheckbox.prototype.id="FieldObjectCheckbox";FieldObjectCheckbox.prototype.fieldDOMName=this.name+"_field";
FieldObjectCheckbox.prototype.getConfigFromElement=function(element){
this.super_FieldObject_getConfigFromElement(element);
this.fieldDOMName=this.elementId+"_field";}
FieldObjectCheckbox.prototype.getFieldHTML=function(){
var displayCode="";
displayCode+=
"<input name='"+this.fieldDOMName+"' "+
"type='checkbox' "+(this.getValue()=="true"?"CHECKED":"")+" "+
"onclick=\""+this.id+".setValue((this.checked?'true':'false'));\" "+
"></input>";
return displayCode;}
FieldObjectCheckbox.prototype._updateAttributes=function(){
var fieldElement=document.getElementsByName(this.fieldDOMName)[0];fieldElement.checked=(this.getValue()=="true"?true : false);}
FieldObjectCheckbox.prototype.isGenerated=function(){
return(document.getElementsByName(this.fieldDOMName).length>0);}
FieldObjectCheckbox.prototype.getValue=function(){
return(this.value=="true"?"true" : "false");}
function FieldObjectCombo(id,elementId){jsClass.extend(this,[FieldObject]);
this.id=id;this.elementId=elementId;}
FieldObjectCombo.prototype.id="FieldObjectCombo";FieldObjectCombo.prototype.answerArray=new Array();FieldObjectCombo.prototype.measurementSystem="IMPERIAL";
FieldObjectCombo.prototype.getConfigFromElement=function(element){
this.super_FieldObject_getConfigFromElement(element);
this.fieldDOMName=this.elementId+"_field";this.answerArray=(element.getAttribute("answersVar")!=undefined?resource.get(element.getAttribute("answersVar")): this.answerArray);}
FieldObjectCombo.prototype.getFieldHTML=function(){
var displayCode="";var answerArray=this.answerArray;
if(answerArray[this.measurementSystem]!=undefined){answerArray=answerArray[this.measurementSystem]}
if(this.isEnabled){
var containerElement=document.getElementById(this.elementId);
displayCode+=
"<select name='"+this.fieldDOMName+"' id='"+this.fieldDOMName+"'"+
"class='"+(this.state==this.FIELD_VALID||!this.isChanged()?this.normalClass : this.errorClass)+"' "+
"style='width:"+parseInt(containerElement.style.width)+"px;height:"+parseInt(containerElement.style.height)+"px;'"+
"onblur=\""+this.id+".setValue(this.value);"+this.id+".onFieldBlur()\" "+
"onfocus=\""+this.id+".onFieldFocus()\" "+
">";
if(this.value==""){displayCode+=
"<option value='' SELECTED"+
">"+resource.get("Questionnaire.Field.PleaseSelectOne")+"</option>";}
for(answer in answerArray){stateClass=this.value==answer?this.selectedClass : this.normalClass;displayCode+=
"<option value='"+answer+"'"+(this.value==answer?" SELECTED" : "")+
">"+answerArray[answer]+"</option>";}
displayCode+="</select>";
}else{
for(answer in answerArray){if(this.value==answer){displayCode+="<span class='"+this.normalClass+"'>"+answerArray[answer]+"</span>";}}}
return displayCode;}
FieldObjectCombo.prototype.generate=function(isForced){
isForced=(isForced!=undefined?isForced : false);
var element=document.getElementById(this.elementId);
if(element!=undefined){
if(this.isGenerated()&&!isForced){
this._updateAttributes();}else{
element.innerHTML=this.getFieldHTML();}}}
FieldObjectCombo.prototype._updateAttributes=function(){
var fieldElement=document.getElementsByName(this.fieldDOMName)[0];
for(i=0;i<fieldElement.options.length;i++){if(fieldElement.options[i].value==this.value){fieldElement.selectedIndex=i;}}
fieldElement.className=this.state==this.FIELD_VALID||!this.isChanged()?this.normalClass : this.errorClass;}
FieldObjectCombo.prototype.isGenerated=function(){
return(document.getElementsByName(this.fieldDOMName).length>0);}
FieldObjectCombo.prototype.setUnitSystem=function(unitSystem){
this.measurementSystem=unitSystem;this.generate(true);}
FieldObjectCombo.prototype.isValid=function(){
var fieldValid=this.super_FieldObject_isValid();var fieldValue=this.getValue();
if(this.isRequired&&fieldValue==""){fieldValid=this.FIELD_ERROR_REQUIRED;}
return fieldValid;}
function FieldObjectEmail(id,elementId){jsClass.extend(this,[FieldObjectText,FieldObject]);
this.id=id;this.elementId=elementId;}
FieldObjectEmail.prototype.id="FieldObjectEmail";
FieldObjectEmail.prototype.isValid=function(){
var fieldValid=this.super_FieldObject_isValid();var fieldValue=this.value;
fieldValid=this.super_FieldObjectText_isValid();
if(fieldValue!=""&&!isEmail(fieldValue)){fieldValid=this.FIELD_ERROR_INVALID_EMAIL;}
return fieldValid;}
function FieldObjectHeight(id,elementId){jsClass.extend(this,[FieldObjectNumeric,FieldObject]);
this.id=id;this.elementId=elementId;
this.suffixMap=resource.get("ModelQuestionnaireUnitSuffixMap");}
FieldObjectHeight.prototype.MAJOR_FIELD=1;FieldObjectHeight.prototype.MINOR_FIELD=2;
FieldObjectHeight.prototype.id="FieldObjectHeight";FieldObjectHeight.prototype.majorValue=0;FieldObjectHeight.prototype.minorValue=0;FieldObjectHeight.prototype.suffixMap=undefined;
FieldObjectHeight.prototype.fieldMajorDOMName="";FieldObjectHeight.prototype.fieldMinorDOMName="";FieldObjectHeight.prototype.units=undefined;
FieldObjectHeight.prototype.getConfigFromElement=function(element){
this.super_FieldObjectNumeric_getConfigFromElement(element);
this.fieldMajorDOMName=this.elementId+"_major_field";this.fieldMinorDOMName=this.elementId+"_minor_field";}
FieldObjectHeight.prototype.generate=function(isForced){
var element=document.getElementById(this.elementId);
if(!this.isGenerated()){
element.innerHTML=this.getFieldHTML();
}else{
this._updateAttributes();}}
FieldObjectHeight.prototype.generate=function(isForced){
isForced=(isForced!=undefined?isForced : false);
var element=document.getElementById(this.elementId);
if(element!=undefined){
if(this.isGenerated()&&!isForced){
this._updateAttributes();}else{
element.innerHTML=this.getFieldHTML();}}}
FieldObjectHeight.prototype.getFieldHTML=function(){
var majorMinorValues=this.getDisplayedMajorMinorValues();
var displayCode="";
displayCode+=
"<input name='"+this.fieldMajorDOMName+"'"+
" type='text'"+
" size='1'"+
" style='position:relative;'"+
" maxlength='1'"+
" class='"+(this.state!=this.FIELD_VALID&&this.isChanged()?this.errorClass : this.normalClass)+"'"+
" onBlur=\""+this.id+".onFieldBlur()\""+
" onFocus=\""+this.id+".onFieldFocus()\""+
" value='"+(majorMinorValues["major"]!=0?majorMinorValues["major"] : "")+"'"+
"></input>";
displayCode+="<span id='"+this.fieldMajorDOMName+"_majorSuffix' style='position:relative;margin:0em 1em 0em 0.5em;'>"+this.suffixMap[this.measurementSystem]["major"]+"</span>";
displayCode+=
"<input name='"+this.fieldMinorDOMName+"'"+
" type='text'"+
" style='position:relative;'"+
" size='2'"+
" maxlength='3'"+
" class='"+(this.state!=this.FIELD_VALID&&this.isChanged()?this.errorClass : this.normalClass)+"'"+
" onBlur=\""+this.id+".onFieldBlur();\""+
" onFocus=\""+this.id+".onFieldFocus();\""+
" value='"+(majorMinorValues["minor"]!=0?majorMinorValues["minor"] : "")+"'"+
"></input>";
displayCode+="<span id='"+this.fieldMinorDOMName+"_minorSuffix' style='position:relative;margin:0em 1em 0em 0.5em;'>"+this.suffixMap[this.measurementSystem]["minor"]+"</span>";
return displayCode;}
FieldObjectHeight.prototype._updateAttributes=function(){
var majorMinorValues=this.getDisplayedMajorMinorValues();
document.getElementsByName(this.fieldMajorDOMName)[0].value=(majorMinorValues["major"]!=0?majorMinorValues["major"] : "0");document.getElementsByName(this.fieldMinorDOMName)[0].value=(majorMinorValues["minor"]!=0?majorMinorValues["minor"] : "0");document.getElementsByName(this.fieldMajorDOMName)[0].className=(this.state!=this.FIELD_VALID&&this.isChanged()?this.errorClass : this.normalClass);document.getElementsByName(this.fieldMinorDOMName)[0].className=(this.state!=this.FIELD_VALID&&this.isChanged()?this.errorClass : this.normalClass);document.getElementById(this.fieldMajorDOMName +"_majorSuffix").innerHTML=this.suffixMap[this.measurementSystem]["major"];document.getElementById(this.fieldMinorDOMName +"_minorSuffix").innerHTML=this.suffixMap[this.measurementSystem]["minor"];this.units=this.suffixMap[this.measurementSystem]["minor"];}
FieldObjectHeight.prototype.isGenerated=function(){
return(document.getElementsByName(this.fieldMajorDOMName).length>0&&
document.getElementsByName(this.fieldMinorDOMName).length>0);}
FieldObjectHeight.prototype.onFieldBlur=function(){
this.setValue(document.getElementsByName(this.fieldMinorDOMName)[0].value,document.getElementsByName(this.fieldMajorDOMName)[0].value);this.super_FieldObject_onFieldBlur();}
FieldObjectHeight.prototype.setValue=function(minorValue,majorValue){
var value=0;var oldValue=this.value;
minorValue=(minorValue.match(/[0-9\.\,]/)?parseFloat(minorValue): 0);majorValue=(majorValue.match(/[0-9\.\,]/)?parseFloat(majorValue): 0);
if(this.measurementSystem==this.UNIT_SYSTEM_METRIC){this.value=Math.round(((majorValue * 100)+minorValue)* this.metricToImperialConversionConstant);}else{this.value=Math.round((majorValue * 12)+minorValue);}
this.state=this.isValid();
if(this.value!=oldValue){
this.generate();    
this.onFieldChange();}
}
FieldObjectHeight.prototype.getDisplayedMajorMinorValues=function(){
var values=new Array();
if(this.value!=undefined&&this.value!=""){
if(this.measurementSystem==this.UNIT_SYSTEM_IMPERIAL||this.mesurementSystem==this.UNIT_SYSTEM_IMPERIAL_STONES){values["major"]=Math.floor(parseFloat(this.value)/ 12);values["minor"]=Math.floor(parseFloat(this.value)-(values["major"] * 12));}else if(this.measurementSystem==this.UNIT_SYSTEM_METRIC){var value=this.value * this.imperialToMetricConversionConstant;values["major"]=Math.floor(parseFloat(value)/ 100);values["minor"]=Math.round(parseFloat(value-(values["major"] * 100)));}
}else{
this.value="";values["minor"]=0;values["major"]=0;}
return values}
function FieldObjectImageList(id,elementId){jsClass.extend(this,[FieldObject]);
this.id=id;this.elementId=elementId;}
FieldObjectImageList.prototype.id="FieldObjectImageList";FieldObjectImageList.prototype.answerArray=new Array();FieldObjectImageList.prototype.itemWidth=20;FieldObjectImageList.prototype.itemHeight=20;FieldObjectImageList.prototype.itemsPerColumn=6;FieldObjectImageList.prototype.highlightClass="";FieldObjectImageList.prototype.selectedClass="";FieldObjectImageList.prototype.imageTokenSrc="@fieldName@_@answerId@.gif";
FieldObjectImageList.prototype.getConfigFromElement=function(element){
this.super_FieldObject_getConfigFromElement(element);
this.answerArray=(element.getAttribute("answersVar")!=undefined?resource.get(element.getAttribute("answersVar")): this.answerArray);this.itemWidth=(element.getAttribute("itemWidth")!=undefined?parseInt(element.getAttribute("itemWidth")): this.itemWidth);this.itemHeight=(element.getAttribute("itemHeight")!=undefined?parseInt(element.getAttribute("itemHeight")): this.itemHeight);this.itemsPerColumn=(element.getAttribute("itemsPerColumn")!=undefined?parseInt(element.getAttribute("itemsPerColumn")): this.itemsPerColumn);this.highlightClass=(element.getAttribute("highlightClass")!=undefined?element.getAttribute("highlightClass"): this.highlightClass);this.selectedClass=(element.getAttribute("selectedClass")!=undefined?element.getAttribute("selectedClass"): this.selectedClass);this.imageTokenSrc=(element.getAttribute("imageTokenSrc")!=undefined?element.getAttribute("imageTokenSrc"): this.imageTokenSrc);}
FieldObjectImageList.prototype.getFieldHTML=function(){
var displayCode="";var stateClass="";var imageSrc="";
for(i=0;i<this.answerArray.length;i++){
stateClass=this.value==this.answerArray[i]?this.selectedClass : this.normalClass;imageSrc=replaceString(this.imageTokenSrc,"@answerId@",this.answerArray[i]);imageSrc=replaceString(imageSrc,"@fieldName@",this.elementId);
displayCode+=
"<img src='"+imageSrc+"'"+
" onclick=\""+this.id+".setValue("+this.answerArray[i]+");"+this.id+".onFieldFocus()\""+
" highlightClass='"+this.highlightClass+"'"+
" selectedClass='"+this.selectedClass+"'"+
" normalClass='"+this.normalClass+"'"+
"style='position:relative;display:inline'"+
" class='"+stateClass+"'"+
" value='"+this.answerArray[i]+"' "+(this.value!=this.answerArray[i]?" onmouseover='this.className=\""+this.highlightClass+"\"'" : "")+
" onmouseout='this.className=\""+stateClass+"\"'"+
"/>";}
return displayCode;}
FieldObjectImageList.prototype._updateAttributes=function(){
var fieldElement=document.getElementsByName(this.elementId)[0];
for(i=0;i<fieldElement.childNodes.length;i++){
if(fieldElement.childNodes[i].value==this.value){
fieldElement.childNodes[i].className=this.selectedClass;fieldElement.childNodes[i].onmouseout=function(){};fieldElement.childNodes[i].onmouseover=function(){};}else{fieldElement.childNodes[i].className=this.normalClass;fieldElement.childNodes[i].onmouseout=function(){this.className=this.normalClass};fieldElement.childNodes[i].onmouseover=function(){this.className=this.highlightClass;};}}}
FieldObjectImageList.prototype.isGenerated=function(){
return(document.getElementById(this.elementId).innerHTML.indexOf("IMG")>0);}
function FieldObjectNumeric(id,elementId){jsClass.extend(this,[FieldObject]);
this.id=id;this.elementId=elementId;}
FieldObjectNumeric.prototype.UNIT_SYSTEM_IMPERIAL="IMPERIAL";FieldObjectNumeric.prototype.UNIT_SYSTEM_METRIC="METRIC";FieldObjectNumeric.prototype.UNIT_SYSTEM_IMPERIAL_STONES="IMPERIALSTONES";
FieldObjectNumeric.prototype.id="FieldObjectNumeric";FieldObjectNumeric.prototype.minValue=-1;FieldObjectNumeric.prototype.maxValue=-1;FieldObjectNumeric.prototype.minLength=-1;FieldObjectNumeric.prototype.maxLength=-1;FieldObjectNumeric.prototype.size=10;FieldObjectNumeric.prototype.format="";FieldObjectNumeric.prototype.measurementSystem="IMPERIAL";FieldObjectNumeric.prototype.units=undefined;FieldObjectNumeric.prototype.suffix=undefined;FieldObjectNumeric.prototype.metricToImperialConversionConstant=0.393700787;FieldObjectNumeric.prototype.imperialToMetricConversionConstant=2.54;FieldObjectNumeric.prototype.fieldDOMName=this.name+"_field";
FieldObjectNumeric.prototype.getConfigFromElement=function(element){
this.super_FieldObject_getConfigFromElement(element);
this.fieldDOMName=this.elementId+"_field";this.minValue=(element.getAttribute("minValue")!=undefined?element.getAttribute("minValue"): this.minValue);this.maxValue=(element.getAttribute("maxValue")!=undefined?element.getAttribute("maxValue"): this.maxValue);this.minLength=(element.getAttribute("minLength")!=undefined?parseInt(element.getAttribute("minLength")): this.minLength);this.maxLength=(element.getAttribute("maxLength")!=undefined?parseInt(element.getAttribute("maxLength")): this.maxLength);this.format=(element.getAttribute("format")!=undefined?element.getAttribute("format"): this.format);this.size=(element.getAttribute("size")!=undefined?parseInt(element.getAttribute("size")): this.size);this.suffix=(element.getAttribute("suffixVar")!=undefined?resource.get(element.getAttribute("suffixVar")): this.suffix);this.units=(this.suffix!=undefined&&this.suffix[this.measurementSystem]!=undefined?this.suffix[this.measurementSystem] : "");}
FieldObjectNumeric.prototype.getFieldHTML=function(){
var displayCode="";
displayCode+=
"<input name='"+this.fieldDOMName+"' "+
"style='position:relative;' "+
"type='text' "+
"size='"+this.size+"' "+(this.maxLength!=-1?"maxlength='"+this.maxLength+"' " : "")+
"class='"+(this.state==this.FIELD_VALID||!this.isChanged()?this.normalClass : this.errorClass)+"' "+
"onblur=\""+this.id+".setValue(this.value);"+this.id+".onFieldBlur()\" "+
"onfocus=\""+this.id+".onFieldFocus()\" ";
if(this.value!=""){displayCode+="value='"+(this.value=="0.00"?"" :(this.measurementSystem==this.UNIT_SYSTEM_METRIC?Math.round(this.value * this.imperialToMetricConversionConstant): Math.round(this.value)))+"' ";}
displayCode+="></input>";
if(this.units!=undefined){displayCode+="<span id=\""+this.fieldDOMName+"_units"+"\" style=\"position:relative;margin:0em 1em 0em 0.5em;\">"+this.units+"</span>";}
return displayCode;}
FieldObjectNumeric.prototype._updateAttributes=function(){
var fieldElement=document.getElementsByName(this.fieldDOMName)[0];
fieldElement.value=(this.value==0?"" :(this.measurementSystem==this.UNIT_SYSTEM_METRIC?Math.round(this.value * this.imperialToMetricConversionConstant): Math.round(this.value)));fieldElement.className=this.state==this.FIELD_VALID||!this.isChanged()?this.normalClass : this.errorClass;
var unitsFieldElement=document.getElementById(this.fieldDOMName+"_units");unitsFieldElement.innerHTML=this.units;}
FieldObjectNumeric.prototype.isGenerated=function(){
return(document.getElementsByName(this.fieldDOMName).length>0);}
FieldObjectNumeric.prototype.getValue=function(){
return convertFractToDecimal(this.value)+"";}
FieldObjectNumeric.prototype.setValue=function(value){
if(this.value!=value){
var element=document.getElementById(this.elementId);if(element!=undefined){
value=(value.match(/[0-9\.\,]/)?parseFloat(value): 0);
if(parseFloat(value)==value){value=Math.round(value*10)/10;}
this.value=(this.measurementSystem==this.UNIT_SYSTEM_METRIC?value * this.metricToImperialConversionConstant : value);this.state=this.isValid();
this.generate();
this.onFieldChange();}}}
FieldObjectNumeric.prototype.isValid=function(){
var fieldValid=this.super_FieldObject_isValid();var fieldValue=this.getValue();
if(this.minLength!=-1&&fieldValue.length==0){
if(this.isRequired){fieldValid=this.FIELD_ERROR_REQUIRED;}
}else if((this.minLength!=-1&&parseInt(fieldValue).length<this.minLength)||(this.maxLength!=-1&&parseInt(fieldValue).length>this.maxLength)){
fieldValid=this.FIELD_ERROR_INVALID_LENGTH;}else{
var numericValue=convertFractToDecimal(fieldValue);
if(isNaN(numericValue)){fieldValid=this.FIELD_ERROR_INVALID_NUMERIC;}
else if((this.minValue!=-1&&parseInt(numericValue)<parseInt(this.minValue))||(this.maxValue!=-1&&parseInt(numericValue)>parseInt(this.maxValue))){fieldValid=this.FIELD_ERROR_INVALID_RANGE;}}
return fieldValid;}
FieldObjectNumeric.prototype.setUnitSystem=function(unitSystem){
this.measurementSystem=unitSystem;this.units=(this.suffix!=undefined&&this.suffix[this.measurementSystem]!=undefined?this.suffix[this.measurementSystem] : "");this.generate();}
function FieldObjectPassword(id,elementId){jsClass.extend(this,[FieldObjectText,FieldObject]);
this.id=id;this.elementId=elementId;}
FieldObjectPassword.prototype.matchWithField=undefined;
FieldObjectPassword.prototype.getConfigFromElement=function(element){
this.super_FieldObjectText_getConfigFromElement(element);
this.matchWithField=(element.getAttribute("matchWithField")!=undefined?element.getAttribute("matchWithField"): this.matchWithField);}
FieldObjectPassword.prototype.getFieldHTML=function(){
var displayCode="";var containerElement=document.getElementById(this.elementId);
displayCode+=
"<input name='"+this.fieldDOMName+"' "+
"type='password' "+
"style='width:"+parseInt(containerElement.style.width)+"px;'"+(this.maxLength!=-1?"maxlength='"+this.maxLength+"' " : "")+
"class='"+(this.state==this.FIELD_VALID||!this.isChanged()?this.normalClass : this.errorClass)+"' "+
"onblur=\""+this.id+".setValue(this.value);"+this.id+".onFieldBlur()\" "+
"onfocus=\""+this.id+".onFieldFocus()\" ";
if(this.value!=""){displayCode+="value='"+this.value+"' ";}
displayCode+="></input>";
return displayCode;}
FieldObjectPassword.prototype.isValid=function(){
var fieldValid=this.super_FieldObjectText_isValid();
if(this.matchWithField!=undefined){
if(this.referenceController!=undefined&&
this.referenceController.fieldObjectMap!=undefined&&
this.referenceController.fieldObjectMap[this.matchWithField]!=undefined){
if(this.getValue()!=this.referenceController.fieldObjectMap[this.matchWithField].getValue()){fieldValid=this.FIELD_ERROR_PASSWORD_DONT_MATCH;}}}
return fieldValid;}
function FieldObjectSlider(id,elementId){jsClass.extend(this,[FieldObject]);
this.id=id;this.elementId=elementId;}
FieldObjectSlider.prototype.id="FieldObjectSlider";FieldObjectSlider.prototype.elementId="";FieldObjectSlider.prototype.ctrlPosition=0;FieldObjectSlider.prototype.sliderLength=100;FieldObjectSlider.prototype.ctrlWidth=10;FieldObjectSlider.prototype.maxValue=100;FieldObjectSlider.prototype.minValue=0;FieldObjectSlider.prototype.gridSize=10;FieldObjectSlider.prototype.ctrlImageUrlHorizontal="../../images/sliderCtrlHorizontal.gif";FieldObjectSlider.prototype.barImageUrlHorizontal="../../images/sliderBackHorizontal.jpg";FieldObjectSlider.prototype.ctrlImageUrlVertical="../../images/sliderCtrlVertical.gif";FieldObjectSlider.prototype.barImageUrlVertical="../../images/sliderBackVertical.jpg";FieldObjectSlider.prototype.maxOffset=undefined;FieldObjectSlider.prototype.minOffset=undefined;FieldObjectSlider.prototype.orientation="HORIZONTAL";FieldObjectSlider.prototype.onDragFunc=undefined;FieldObjectSlider.prototype.onDropFunc=undefined;FieldObjectSlider.prototype.onPickFunc=undefined;
FieldObjectSlider.prototype.init=function(){
this.getConfigFromElement(document.getElementById(this.elementId));
this.maxOffset=this.sliderLength-(this.ctrlWidth);this.minOffset=0;
if(document.getElementById(this.id+"sliderCtrl")==undefined){
this.generate(true);
DragDrop.doDrag(this.id+"sliderCtrl",{"containerElementId":this.elementId,"onPick":this.id+".onPick()","onDrag":this.id+".onDrag()","onDrop":this.id+".onDrop()"});}
if(this.value!=undefined){this.setValue(this.value,true);}}
FieldObjectSlider.prototype.getConfigFromElement=function(element){
this.maxValue=(element.getAttribute("maxValue")!=undefined?element.getAttribute("maxValue"): this.maxValue);this.minValue=(element.getAttribute("minValue")!=undefined?element.getAttribute("minValue"): this.minValue);this.gridSize=(element.getAttribute("gridSize")!=undefined?element.getAttribute("gridSize"): this.gridSize);
if(parseInt(element.style.height)>parseInt(element.style.width)){this.sliderLength=parseInt(element.style.height);this.orientation="VERTICAL"}else{this.sliderLength=parseInt(element.style.width);this.orientation="HORIZONTAL";}
this.onDragFunc=(element.getAttribute("onDragFunc")!=undefined?element.getAttribute("onDragFunc"): function(){});this.onDropFunc=(element.getAttribute("onDropFunc")!=undefined?element.getAttribute("onDropFunc"): function(){});this.onPickFunc=(element.getAttribute("onPickFunc")!=undefined?element.getAttribute("onPickFunc"): function(){});
this.value=(element.getAttribute("value")!=undefined?element.getAttribute("value"): this.value);}
FieldObjectSlider.prototype.getFieldHTML=function(){
var displayCode="";
if(this.orientation=="HORIZONTAL"){displayCode='<div id="'+this.id+'sliderBar" style="position:absolute;background-position: 10 0;top:0px;left:0px;height:15px;width:'+this.sliderLength+'px;background-repeat:repeat-x;background-image:URL(\''+this.barImageUrlHorizontal+'\');" class="sliderBack">';displayCode+='</div><div id="'+this.id+'sliderCtrl" varName="'+this.id+'" style="position:absolute;left:0px;top:0px;width:11px;height:20px;" class="sliderCtrl">';displayCode+='<img src="'+this.ctrlImageUrlHorizontal+'"></img></div>';}else{displayCode='<div id="'+this.id+'sliderBar" style="position:absolute;background-position: 0 10;top:0px;left:0px;height:'+this.sliderLength+'px;width:15px;background-repeat:repeat-y;background-image:URL(\''+this.barImageUrlVertical+'\');" class="sliderBack">';displayCode+='</div><div id="'+this.id+'sliderCtrl" varName="'+this.id+'" style="position:absolute;left:0px;top:0px;width:11px;height:20px;" class="sliderCtrl">';displayCode+='<img src="'+this.ctrlImageUrlVertical+'"></img></div>';}
return displayCode;}
FieldObjectSlider.prototype.disable=function(){
this.isEnabled=false;
}
FieldObjectSlider.prototype.enable=function(){
this.isEnabled=true;
}
FieldObjectSlider.prototype.getValue=function(){
return(this.getValueFromPosition());}
FieldObjectSlider.prototype.setValue=function(value,isForcedPosition){
isForcedPosition=isForcedPosition!=undefined?isForcedPosition : false;
this.value=value;document.getElementById(this.elementId).value=this.value;
if(isForcedPosition){this.updateCtrlPosition();}
}
FieldObjectSlider.prototype.isValid=function(){
var fieldValid=this.super_FieldObject_isValid();var fieldValue=this.getValue();
if(this.isRequired&&fieldValue==""){fieldValid=this.FIELD_ERROR_REQUIRED;}
return fieldValid;}
FieldObjectSlider.prototype.updateCtrlPosition=function(){
var oldPosition=this.ctrlPosition;this.ctrlPosition=this.getPositionFromValue();
var diff=parseInt(this.ctrlPosition)-parseInt(oldPosition);
var ctrlElement=document.getElementById(this.id+"sliderCtrl");
if(this.orientation=="HORIZONTAL"){
ctrlElement.style.left=parseInt(this.ctrlPosition)+"px";}else{
ctrlElement.style.top=parseInt(this.ctrlPosition)+"px";}}
FieldObjectSlider.prototype.getValueFromPosition=function(){
return parseInt(((parseInt(this.ctrlPosition)/(parseInt(this.sliderLength)-parseInt(this.ctrlWidth)))*(parseInt(this.maxValue)-parseInt(this.minValue)))+parseInt(this.minValue));}
FieldObjectSlider.prototype.getPositionFromValue=function(){
return((parseInt(this.value)-parseInt(this.minValue))/(parseInt(this.maxValue)-parseInt(this.minValue)))*(parseInt(this.sliderLength)-parseInt(this.ctrlWidth));}
FieldObjectSlider.prototype.onDrag=function(){
if(this.orientation=="HORIZONTAL"){this.ctrlPosition=parseInt(document.getElementById(this.id+"sliderCtrl").style.left);}else{this.ctrlPosition=parseInt(document.getElementById(this.id+"sliderCtrl").style.top);}
this.value=this.getValueFromPosition();
document.getElementById(this.elementId).value=this.value;
if(this.onDragFunc){eval(this.onDragFunc);}}
FieldObjectSlider.prototype.onDrop=function(){
if(this.onDropFunc){eval(this.onDropFunc);}}
FieldObjectSlider.prototype.onPick=function(){
if(this.onPickFunc){eval(this.onPickFunc);}}
function FieldObjectText(id,elementId){jsClass.extend(this,[FieldObject]);
this.id=id;this.elementId=elementId;}
FieldObjectText.prototype.id="FieldObjectText";FieldObjectText.prototype.minValue=0;FieldObjectText.prototype.maxValue=-1;FieldObjectText.prototype.minLength=1;FieldObjectText.prototype.maxLength=-1;FieldObjectText.prototype.size=10;FieldObjectText.prototype.format="alphanumeric";FieldObjectText.prototype.isMultiline=false;
FieldObjectText.prototype.getConfigFromElement=function(element){
this.super_FieldObject_getConfigFromElement(element);
this.fieldDOMName=this.elementId+"_field";this.minValue=(element.getAttribute("minValue")!=undefined?element.getAttribute("minValue"): this.minValue);this.maxValue=(element.getAttribute("maxValue")!=undefined?element.getAttribute("maxValue"): this.maxValue);this.minLength=(element.getAttribute("minLength")!=undefined?parseInt(element.getAttribute("minLength")): this.minLength);this.maxLength=(element.getAttribute("maxLength")!=undefined?parseInt(element.getAttribute("maxLength")): this.maxLength);this.format=(element.getAttribute("format")!=undefined?element.getAttribute("format"): this.format);this.size=(element.getAttribute("size")!=undefined?parseInt(element.getAttribute("size")): this.size);this.isMultiline=(element.getAttribute("isMultiline")!=undefined&&element.getAttribute("isMultiline")=="true"?true : false);}
FieldObjectText.prototype._updateAttributes=function(){
var fieldElement=document.getElementsByName(this.fieldDOMName)[0];this.value=ParserUtils.parseHtml(this.value);fieldElement.value=this.value;fieldElement.disabled=!this.isEnabled;fieldElement.className=this.state==this.FIELD_VALID||!this.isChanged()?this.normalClass : this.errorClass;}
FieldObjectText.prototype.isGenerated=function(){
return(document.getElementsByName(this.fieldDOMName).length>0);}
FieldObjectText.prototype.getFieldHTML=function(){
var displayCode="";var containerElement=document.getElementById(this.elementId);
this.value=ParserUtils.parseHtml(this.value);
if(this.isMultiline){displayCode=
"<textarea name='"+this.fieldDOMName+"' "+
"style='width:"+parseInt(containerElement.style.width)+"px;height:"+parseInt(containerElement.style.height)+"px;'"+(this.maxLength!=-1?"maxlength='"+this.maxLength+"' " : "")+
"class='"+(this.state==this.FIELD_VALID||!this.isChanged()?this.normalClass : this.errorClass)+"' "+(this.isEnabled==true?" " : " disabled ")+
"onblur=\""+this.id+".setValue(this.value);"+this.id+".onFieldBlur()\" "+
"onfocus=\""+this.id+".onFieldFocus()\" "+
">"+(this.value!=""?this.value : "")+
"</textarea>";
}else{displayCode=
"<input name='"+this.fieldDOMName+"' "+
"type='text' "+
"style='width:"+parseInt(containerElement.style.width)+"px;height:"+parseInt(containerElement.style.height)+"px;'"+(this.maxLength!=-1?"maxlength='"+this.maxLength+"' " : "")+
"class='"+(this.state==this.FIELD_VALID||!this.isChanged()?this.normalClass : this.errorClass)+"' "+(this.isEnabled==true?" " : " disabled ")+
"onblur=\""+this.id+".setValue(this.value);"+this.id+".onFieldBlur()\" "+
"onfocus=\""+this.id+".onFieldFocus()\" "+(this.value!=""?"value='"+this.value+"' " : "")+
"></input>";}
return displayCode;}
FieldObjectText.prototype.isValid=function(){
var fieldValid=this.super_FieldObject_isValid();var fieldValue=this.value;
if(this.isRequired==true||(this.isRequired==false&&fieldValue.length>0)){
if((this.minLength!=-1&&fieldValue.length<this.minLength)||(this.maxLength!=-1&&fieldValue.length>this.maxLength)){fieldValid=this.FIELD_ERROR_INVALID_LENGTH;}
if(this.format=="alphanumeric"&&trim(fieldValue).match(/([a-zA-Z0-9������������������������Ԍ��ܟ�\-\_\ \.\-\@\!\?\(\)\[\]\n\r]*)/)[0]!=fieldValue){fieldValid=this.FIELD_ERROR_INVALID_CHARACTERS;}
if(this.isRequired==true&&fieldValue.length==0){fieldValid=this.FIELD_ERROR_REQUIRED;}}
return fieldValid;}
FieldObjectText.prototype.setValue=function(value,isForced){(isForced!=undefined?isForced : false);
value=value+"";
if(this.value!=value){
this.value=value;
var newState=this.isValid();
this.state=newState
this.generate(isForced);
this.onFieldChange();}}
function FieldObjectWeight(id,elementId){jsClass.extend(this,[FieldObjectNumeric,FieldObject]);
this.id=id;this.elementId=elementId;}
FieldObjectWeight.prototype.id="FieldObjectWeight";FieldObjectWeight.prototype.metricToImperialConversionConstant=2.20462262;FieldObjectWeight.prototype.imperialToMetricConversionConstant=0.45359237;FieldObjectWeight.prototype.poundsToStonesConversionConstant=14.0;
FieldObjectWeight.prototype.minValue= 30;FieldObjectWeight.prototype.maxValue=300;
FieldObjectWeight.prototype.minorValue=0;FieldObjectWeight.prototype.majorValue=0;
FieldObjectWeight.prototype.fieldMajorDOMName="";FieldObjectWeight.prototype.fieldMajorDOMName="";
FieldObjectWeight.prototype.MIN_BMI_VALUE=18;
FieldObjectWeight.prototype.getConfigFromElement=function(element){
this.super_FieldObjectNumeric_getConfigFromElement(element);
this.fieldMajorDOMName=this.elementId+"_major_field";this.fieldMinorDOMName=this.elementId+"_minor_field";}
FieldObjectWeight.prototype.getFieldHTML=function(){
this.updateInternalMajorMinor();
if(this.measurementSystem==this.UNIT_SYSTEM_IMPERIAL_STONES){
this.setValue(this.value);
var minorPrefix=this.units.substring(this.units.indexOf("|")+1);var majorPrefix=this.units.substring(0,this.units.indexOf("|"));
var displayCode="";
displayCode+=
"<input name='"+this.fieldMajorDOMName+"' "+
"style='position:relative;margin-right:0.5em;' "+
"type='text' "+
"size='3' "+(this.maxLength!=-1?"maxlength='"+this.maxLength+"' " : "")+
"class='"+(this.state==this.FIELD_VALID||!this.isChanged()?this.normalClass : this.errorClass)+"' "+
"onblur=\""+this.id+".setValue(this.value,'major');"+this.id+".onFieldBlur()\" "+
"onfocus=\""+this.id+".onFieldFocus()\" ";
if(this.value!=""){displayCode+="value='"+this.majorValue+"' ";}
displayCode+="></input><span style='margin-right:0.5em'>"+ majorPrefix+"</span>";
displayCode+="<input name='"+this.fieldMinorDOMName+"' "+
"style='position:relative;margin-right:0.5em;' "+
"type='text' "+
"size='3' "+(this.maxLength!=-1?"maxlength='"+this.maxLength+"' " : "")+
"class='"+(this.state==this.FIELD_VALID||!this.isChanged()?this.normalClass : this.errorClass)+"' "+
"onblur=\""+this.id+".setValue(this.value,'minor');"+this.id+".onFieldBlur()\" "+
"onfocus=\""+this.id+".onFieldFocus()\" ";
if(this.value!=""){displayCode+="value='"+this.minorValue+"' ";}
displayCode+="></input>";
if(this.units!=undefined){displayCode+="<span>"+minorPrefix+"</span>";}
return displayCode;
}else{
return this.super_FieldObjectNumeric_getFieldHTML();}}
FieldObjectWeight.prototype._updateAttributes=function(){
if(this.measurementSystem==this.UNIT_SYSTEM_IMPERIAL_STONES){
var fieldElementMajor=document.getElementsByName(this.fieldMajorDOMName)[0];var fieldElementMinor=document.getElementsByName(this.fieldMinorDOMName)[0];
fieldElementMajor.value=this.majorValue;fieldElementMinor.value=this.minorValue;
fieldElementMajor.className=this.state==this.FIELD_VALID||!this.isChanged()?this.normalClass : this.errorClass;fieldElementMinor.className=this.state==this.FIELD_VALID||!this.isChanged()?this.normalClass : this.errorClass;}else{
return this.super_FieldObjectNumeric__updateAttributes();}}
FieldObjectWeight.prototype.isGenerated=function(){
if(this.measurementSystem==this.UNIT_SYSTEM_IMPERIAL_STONES){return(document.getElementsByName(this.fieldMajorDOMName).length>0&&
document.getElementsByName(this.fieldMinorDOMName).length>0);}else{
return this.super_FieldObjectNumeric_isGenerated();}}
FieldObjectWeight.prototype.getValue=function(){
return convertFractToDecimal(this.value)+"";}
FieldObjectWeight.prototype.updateInternalMajorMinor=function(){
this.majorValue=parseInt((this.value / 14.0));this.minorValue=parseInt(this.value % 14.0);}
FieldObjectWeight.prototype.setValue=function(value,pOption){
var oldValue=this.value;value=isNaN(parseInt(value))?"0" : value;
if(pOption=="major"&&this.majorValue!=value){
this.majorValue=value;
this.value=(this.majorValue!=""?parseInt(this.majorValue * 14): 0)+(this.minorValue!=""?parseInt(this.minorValue): 0);}else if(pOption=="minor"&&this.minorValue!=value){
this.minorValue=value;this.value=(this.majorValue!=""?parseInt(this.majorValue * 14): 0)+(this.minorValue!=""?parseInt(this.minorValue): 0);}else if(pOption==undefined&&this.value!=value){
var element=document.getElementById(this.elementId);if(element!=undefined){
value=(value.match(/[0-9\.\,]/)?parseFloat(value): 0);
if(parseFloat(value)==value){value=Math.round(value*10)/10;}
this.value=(this.measurementSystem==this.UNIT_SYSTEM_METRIC?value * this.metricToImperialConversionConstant : value);}}
this.checkBMI();
this.updateInternalMajorMinor();this.state=this.isValid();
if(this.value!=oldValue){
this.generate();    
this.onFieldChange();}}
FieldObjectWeight.prototype.checkBMI=function(){
if(this.referenceController!=undefined&&this.referenceController.MIN_BMI_VALUE!=undefined&&this.referenceController.getMetricHeightValue!=undefined){
var isBMIValid=this.validateBMI(this.referenceController.getMetricHeightValue(),this.referenceController.MIN_BMI_VALUE);
if(!isBMIValid){Workspace.events.throwEvent(
Workspace.events.EVENT_BMI_REAJUSTED,
this);}}}
FieldObjectWeight.prototype.validateBMI=function(heightMetricValue,minBMIValue){
var isBMIRanged=true;minBMIValue=minBMIValue==undefined?this.MIN_BMI_VALUE : minBMIValue;
if(heightMetricValue!=undefined){
var modelBMI=0;var weightValue=parseInt(this.getValue()) * 0.454;var heightValue=parseInt(heightMetricValue);
modelBMI=weightValue /(heightValue  * heightValue)* 10000;
if(modelBMI<minBMIValue){
recalculateBMIWeight=(this.MIN_BMI_VALUE / 10000.0)*(heightValue  * heightValue);
isBMIRanged=false;
var newWeight=Math.ceil(recalculateBMIWeight * 2.2);
this.value=newWeight;this.majorValue=Math.ceil((this.value / 14.0));this.minorValue=Math.ceil(this.value % 14.0);
this.generate();}}
return isBMIRanged;}
function FieldObjectYear(id,elementId){jsClass.extend(this,[FieldObjectNumeric,FieldObject]);
this.id=id;this.elementId=elementId;}
FieldObjectYear.prototype.id="FieldObjectYear";FieldObjectYear.measurementSystem="";
FieldObjectYear.prototype.setUnitSystem=function(unitSystem){}
function AnimationController(id){
this.id=id;this.groupMap=new Array();
return this;}
AnimationController.prototype.CYCLE_TIME=300;AnimationController.prototype.STATE_HOVER_ON="on";AnimationController.prototype.STATE_HOVER_OFF="off";AnimationController.prototype.STATE_ALTERNATE_ON="open";AnimationController.prototype.STATE_ALTERNATE_OFF="closed";AnimationController.prototype._cssAttributes=undefined;AnimationController.prototype._cssText=undefined;
AnimationController.prototype.id="AnimationController";AnimationController.prototype.groupMap=undefined;
AnimationController.prototype.getElementCSSAttributes=function(elementId){
if(this._cssText==undefined){
this._cssText="";
for(var i=0;i<document.styleSheets.length;i++){this._cssText+=document.styleSheets[i].cssText}}
var attributes=new Array();
if(this._cssText.indexOf(elementId)>-1){
var cssText=new RegExp("#"+elementId+"\\s\\{([^\\}]*)\\}","g").exec(this._cssText.replace(/[\n\r]/g,""))[1];
if(cssText!=undefined){var cssAttributes=cssText.match(/[A-Za-z]+\:\s?[^\;\t]*/g);var attributeInfo=undefined;
for(var i=0;i<cssAttributes.length;i++){attributeInfo=cssAttributes[i].match(/([^\:]*)\:\s?(.*)/);attributes[attributeInfo[1].toLowerCase()]=attributeInfo[2];}}}
var element=document.getElementById(elementId);if(element!=undefined){element._cssAttributes=attributes;}
return attributes;}
AnimationController.prototype._define=function(element){
element.isDefined=true;
var cssAttributes=this.getElementCSSAttributes(element.id);
element.onComplete=(element.getAttribute("onAnimationComplete")!=undefined?element.getAttribute("onAnimationComplete"):undefined);
element.oClass=element.className;element.tClass=element.getAttribute("tClass");
element.oZIndex=element.style.zIndex;
element.tZIndex=(cssAttributes["tZIndex"]!=undefined?cssAttributes["tZIndex"] 
:(element.style.tZIndex!=undefined?element.style.tZIndex : element.getAttribute("tZIndex")));
if(element.style.position!="relative"&&isNaN(parseInt(element.style.left))&&!isNaN(parseInt(element.offsetLeft))){element.oLeft=parseInt(element.offsetLeft);}else if(!isNaN(parseInt(element.style.left))){element.oLeft=parseInt(element.style.left);}else{element.oLeft=0;}
if(element.style.position!="relative"&&isNaN(parseInt(element.style.top))&&!isNaN(parseInt(element.offsetTop))){element.oTop=parseInt(element.offsetTop);}else if(!isNaN(parseInt(element.style.top))){element.oTop=parseInt(element.style.top);}else{element.oTop=0;}
element.oWidth=parseInt(cssAttributes["width"]!=undefined?cssAttributes["width"]
: getWidth(element));
element.oHeight=parseInt(cssAttributes["height"]!=undefined?cssAttributes["height"]
: getHeight(element));
element.tLeft=parseInt(cssAttributes["tleft"]!=undefined?cssAttributes["tleft"]
:(element.getAttribute("tLeft")!=undefined?element.getAttribute("tLeft"): element.oLeft));
element.tTop=parseInt(cssAttributes["ttop"]!=undefined?cssAttributes["ttop"]
:(element.getAttribute("tTop")!=undefined?element.getAttribute("tTop"): element.oTop));
element.tWidth=parseInt(cssAttributes["twidth"]!=undefined?cssAttributes["twidth"]
:(element.getAttribute("tWidth")!=undefined?element.getAttribute("tWidth"): element.oWidth));
element.tHeight=parseInt(cssAttributes["theight"]!=undefined?cssAttributes["theight"] 
:(element.getAttribute("tHeight")!=undefined?element.getAttribute("tHeight"): element.oHeight));
element.state=this.STATE_ALTERNATE_OFF;
element.groupName=(cssAttributes["groupname"]!=undefined?cssAttributes["groupname"]
:(element.getAttribute("groupName")!=undefined?element.getAttribute("groupName")
:(element.getAttribute("group_name")!=undefined?element.getAttribute("group_name"): undefined)));
this.registerElementIdInGroup(element.id,element.groupName);}
AnimationController.prototype.registerElementIdInGroup=function(elementId,groupName){
if(groupName!=undefined){
if(this.groupMap[groupName]==undefined){this.groupMap[groupName]=new Array();}
this.groupMap[groupName].push(elementId);}}
AnimationController.prototype.openAndClose=function(elementId,isQuickMode){
quickMode=(isQuickMode!=undefined&&isQuickMode==true?true : false);
var element=document.getElementById(elementId);
if(element!=undefined){
if(element.isDefined==undefined){this._define(element);}
this.resetAll(element.groupName,new Array(elementId),quickMode);
if(element.state==this.STATE_ALTERNATE_OFF){this.open(elementId);
}else if(element.state==this.STATE_ALTERNATE_ON){this.reset(elementId);}
}else{log.error("element '"+elementId+"' is undefined",this);}}
AnimationController.prototype.openSingle=function(elementId,isQuickMode){
quickMode=(isQuickMode!=undefined&&isQuickMode==true?true : false);
var element=document.getElementById(elementId);
if(element!=undefined){
if(element.isDefined==undefined){this._define(element);}
this.resetAll(element.groupName,new Array(elementId),quickMode);element.thread=setTimeout(this.id+".open('"+elementId+"',undefined,"+quickMode+")",1);}}
AnimationController.prototype.open=function(elementId,isQuickMode){
quickMode=(isQuickMode!=undefined&&isQuickMode==true?true : false);
var element=document.getElementById(elementId);
if(element!=undefined){
if(element.isDefined==undefined){this._define(element);}
element.state=this.STATE_ALTERNATE_ON;
if(element.tZIndex!=undefined){element.style.zIndex=element.tZIndex;}
if(element.thread!=undefined){clearTimeout(element.thread);}
var onComplete=(element.getAttribute("onOpen")!=undefined?element.getAttribute("onOpen"):(element.getAttribute("onopen")!=undefined?element.getAttribute("onopen"): element.onComplete));
var attributes=new Array();attributes["tLeft"]=element.tLeft;attributes["tTop"]=element.tTop;attributes["tWidth"]=element.tWidth;attributes["tHeight"]=element.tHeight;attributes["tClass"]=element.tClass;attributes["onComplete"]=onComplete;
if(quickMode){attributes["duration"]=0;}
this.animateElement(elementId,attributes);}else{log.error("element '"+elementId+"' is undefined",this);}}
AnimationController.prototype.reset=function(elementId,isQuickMode){
quickMode=(isQuickMode!=undefined&&isQuickMode==true?true : false);
var element=document.getElementById(elementId);
if(element!=undefined){
if(element.isDefined==undefined){this._define(element);}
element.state=this.STATE_ALTERNATE_OFF;element.style.zIndex=element.oZIndex;
var onComplete=(element.getAttribute("onClose")!=undefined?element.getAttribute("onClose"):(element.getAttribute("onclose")!=undefined?element.getAttribute("onclose"): element.onComplete));
var attributes=new Array();attributes["tLeft"]=element.oLeft;attributes["tTop"]=element.oTop;attributes["tWidth"]=element.oWidth;attributes["tHeight"]=element.oHeight;attributes["tClass"]=element.oClass;attributes["onComplete"]=onComplete;
if(quickMode){attributes["duration"]=0;}
this.animateElement(elementId,attributes);}else{log.error("element '"+elementId+"' is undefined",this);}}
AnimationController.prototype.resetAll=function(groupName,pExceptionArray,isQuickMode){
if(groupName!=undefined){
var groupList=this.groupMap[groupName];var exceptionList="|"+(pExceptionArray!=undefined?pExceptionArray : new Array()).join("|")+"|";
if(groupList!=undefined){for(var i=0;i<groupList.length;i++){if(exceptionList.indexOf("|"+groupList[i]+"|")==-1){
tmpAnimatedDiv=document.getElementById(groupList[i]);if(tmpAnimatedDiv.state==this.STATE_ALTERNATE_ON){
this.reset(groupList[i],isQuickMode);}}}}                   }}
AnimationController.prototype.animateElement=function(elementId,attributes){
var element=document.getElementById(elementId);
if(element!=undefined&&attributes!=undefined){
if(element.isDefined==undefined){this._define(element);}
attributes["sLeft"]=(attributes["sLeft"]!=undefined?attributes["sLeft"] :(!isNaN(parseInt(element.style.left))?parseInt(element.style.left): element.oLeft));attributes["sTop"]=(attributes["sTop"]!=undefined?attributes["sTop"] :(!isNaN(parseInt(element.style.top))?parseInt(element.style.top): element.oTop));attributes["sWidth"]=(attributes["sWidth"]!=undefined?attributes["sWidth"] :(!isNaN(parseInt(element.style.width))?parseInt(element.style.width): element.oWidth));attributes["sHeight"]=(attributes["sHeight"]!=undefined?attributes["sHeight"] :(!isNaN(parseInt(element.style.height))?parseInt(element.style.height): element.oHeight));
attributes["sOpacity"]=(attributes["sOpacity"]!=undefined?attributes["sOpacity"] : element.getAttribute("sOpacity")?element.getAttribute("sOpacity"): undefined);attributes["tOpacity"]=(attributes["tOpacity"]!=undefined?attributes["tOpacity"] : element.getAttribute("tOpacity")?element.getAttribute("tOpacity"): undefined);
if(attributes["mLeft"]!=undefined){attributes["tLeft"]=attributes["sLeft"]+attributes["mLeft"];}
if(attributes["mTop"]!=undefined){attributes["tTop"]=attributes["sTop"]+attributes["mTop"];}
this._animate(
elementId,attributes,true);}}
AnimationController.prototype._animate=function(elementId,animAttributes,isStartingCall){
var isTargetReached=true;var element=document.getElementById(elementId);
if(element!=undefined&&(animAttributes!=undefined||element._animationAttributes!=undefined)){
var animAttributes=(animAttributes!=undefined?animAttributes : element._animationAttributes);
if(isStartingCall){
animAttributes["startAnimationTime"]=new Date().getTime();animAttributes["frameIndex"]=0;
if(animAttributes["sOpacity"]!=undefined&&animAttributes["tOpacity"]!=undefined&&animAttributes["sOpacity"]!=animAttributes["tOpacity"]){
animAttributes["cOpacity"]=animAttributes["sOpacity"];this.setOpacity(element,parseInt(animAttributes["cOpacity"]));}
if(animAttributes["sLeft"]!=undefined&&animAttributes["tLeft"]!=undefined&&animAttributes["sLeft"]!=animAttributes["tLeft"]){
animAttributes["cLeft"]=parseInt(animAttributes["sLeft"]);element.style.left=animAttributes["cLeft"]+"px";}
if(animAttributes["sTop"]!=undefined&&animAttributes["tTop"]!=undefined&&animAttributes["sTop"]!=animAttributes["tTop"]){
animAttributes["cTop"]=parseInt(animAttributes["sTop"]);element.style.top=animAttributes["cTop"]+"px";}
if(animAttributes["sWidth"]!=undefined&&animAttributes["tWidth"]!=undefined&&animAttributes["sWidth"]!=animAttributes["tWidth"]){
animAttributes["cWidth"]=parseInt(animAttributes["sWidth"]);element.style.width=animAttributes["cWidth"]+"px";}
if(animAttributes["sHeight"]!=undefined&&animAttributes["tHeight"]!=undefined&&animAttributes["sHeight"]!=animAttributes["tHeight"]){
animAttributes["cHeight"]=parseInt(animAttributes["sHeight"]);element.style.height=animAttributes["cHeight"]+"px";}}
if(animAttributes["duration"]==undefined){animAttributes["duration"]=this.CYCLE_TIME;}
animAttributes["frameIndex"]++;
var averagetimePerFrame=(new Date().getTime()-animAttributes["startAnimationTime"])/ animAttributes["frameIndex"];if(averagetimePerFrame==0){averagetimePerFrame=10;}
var remainingTime=(animAttributes["startAnimationTime"]+animAttributes["duration"])-new Date().getTime();var remainingFrames=remainingTime/averagetimePerFrame;
if(element.thread!=undefined){clearTimeout(element.thread);}
if(animAttributes["cLeft"]!=undefined){var deltaLeft=(animAttributes["tLeft"]-animAttributes["sLeft"])/ remainingFrames;
if((deltaLeft>0&&animAttributes["cLeft"]+deltaLeft<animAttributes["tLeft"])||(deltaLeft<0&&animAttributes["cLeft"]+deltaLeft>animAttributes["tLeft"])){animAttributes["cLeft"]=animAttributes["cLeft"]+deltaLeft;element.style.left=parseInt(animAttributes["cLeft"])+"px";isTargetReached=false;}}
if(animAttributes["cTop"]!=undefined){var deltaTop=(animAttributes["tTop"]-animAttributes["sTop"])/ remainingFrames;
if((deltaTop>0&&animAttributes["cTop"]+deltaTop<animAttributes["tTop"])||(deltaTop<0&&animAttributes["cTop"]+deltaTop>animAttributes["tTop"])){animAttributes["cTop"]=animAttributes["cTop"]+deltaTop;element.style.top=parseInt(animAttributes["cTop"])+"px";isTargetReached=false;}}
if(animAttributes["cWidth"]!=undefined){var deltaWidth=(animAttributes["tWidth"]-animAttributes["sWidth"])/ remainingFrames;
if(animAttributes["cWidth"]+deltaWidth<0){deltaWidth=animAttributes["cWidth"];}
if((deltaWidth>0&&animAttributes["cWidth"]+deltaWidth<animAttributes["tWidth"])||(deltaWidth<0&&animAttributes["cWidth"]+deltaWidth>animAttributes["tWidth"])){animAttributes["cWidth"]=animAttributes["cWidth"]+deltaWidth;element.style.width=parseInt(animAttributes["cWidth"])+"px";isTargetReached=false;}}
if(animAttributes["cHeight"]!=undefined){var deltaHeight=(animAttributes["tHeight"]-animAttributes["sHeight"])/ remainingFrames;
if(animAttributes["cHeight"]+deltaHeight<0){deltaHeight=animAttributes["cHeight"];}
if((deltaHeight>0&&animAttributes["cHeight"]+deltaHeight<animAttributes["tHeight"])||(deltaHeight<0&&animAttributes["cHeight"]+deltaHeight>animAttributes["tHeight"])){animAttributes["cHeight"]=animAttributes["cHeight"]+deltaHeight;element.style.height=parseInt(animAttributes["cHeight"])+"px";isTargetReached=false;}}
if(animAttributes["cOpacity"]!=undefined){
if(animAttributes["sOpacity"]<animAttributes["tOpacity"]){animAttributes["cOpacity"]+=(animAttributes["tOpacity"]-animAttributes["sOpacity"])/ remainingFrames;}else if(animAttributes["sOpacity"]>animAttributes["tOpacity"]){animAttributes["cOpacity"]-=(animAttributes["sOpacity"]-animAttributes["tOpacity"])/ remainingFrames;}
if((animAttributes["sOpacity"]<animAttributes["tOpacity"]&&animAttributes["cOpacity"]<animAttributes["tOpacity"])||(animAttributes["sOpacity"]>animAttributes["tOpacity"]&&animAttributes["cOpacity"]>animAttributes["tOpacity"])){this.setOpacity(element,parseInt(animAttributes["cOpacity"]));isTargetReached=false;}}
element._animationAttributes=animAttributes;
if(remainingFrames>0&&!isTargetReached){element.thread=setTimeout(this.id+"._animate('"+elementId+"')",10);}else{
if(animAttributes["cLeft"]!=undefined){element.style.left=animAttributes["tLeft"]+"px";}
if(animAttributes["cTop"]!=undefined){element.style.top=animAttributes["tTop"]+"px";}
if(animAttributes["cWidth"]!=undefined){element.style.width=animAttributes["tWidth"]+"px";}
if(animAttributes["cHeight"]!=undefined){element.style.height=animAttributes["tHeight"]+"px";}
if(animAttributes["tClass"]!=undefined){element.className=animAttributes["tClass"];}
if(animAttributes["cOpacity"]!=undefined){this.setOpacity(element,animAttributes["tOpacity"]);}
if(animAttributes["onComplete"]!=undefined){eval(animAttributes["onComplete"]);}}}}
AnimationController.prototype.stopElementAnimation=function(elementId){
var element=document.getElementById(elementId);if(element!=undefined&&element.thread!=undefined){clearTimeout(element.thread);element.thread=undefined;}}
AnimationController.prototype.clearGroup=function(groupName){
this.groupMap[groupName]=undefined;}
AnimationController.prototype.registerGroup=function(groupName,elementIdArray){
this.groupMap[groupName]=elementIdArray;}
AnimationController.prototype.setImageState=function(elementId,attribute,value){
var element=document.getElementById(elementId);
if(element!=undefined&&element.getAttribute("src_token")!=undefined){
var tmpArray=element.src.split("/");var fileExtension="."+tmpArray[tmpArray.length-1].split(".")[1];var originalFilename=tmpArray.pop().split(".")[0];var filePrefix=tmpArray.join("/")+"/";var originalSrcArray=originalFilename.split("_");
var tmpArray=element.getAttribute("src_token").split("/");var tokenedSrcArray=tmpArray.pop().split(".")[0].split("_");
for(var i=0;i<tokenedSrcArray.length;i++){if(tokenedSrcArray[i]==attribute){originalSrcArray[i]=value;}}
element.src=filePrefix+originalSrcArray.join("_")+fileExtension;}}
AnimationController.prototype.isOpen=function(elementId){
var element=document.getElementById(elementId);
if(element!=undefined&&element.state==this.STATE_ALTERNATE_ON){return true;}else{return false;}}
AnimationController.prototype.scale=function(elementId,centerX,centerY,pRatio){
var element=document.getElementById(elementId);
if(element!=undefined){
if(element.isDefined==undefined){this._define(element);}
var tLeft=parseInt((element.oWidth/2)-(centerX*pRatio));var tTop=parseInt((element.oHeight/2)-(centerY*pRatio));
if(tLeft>0){tLeft=0;}
if(tTop>0){tTop=0;}
if(tLeft<(element.oWidth*(pRatio-1)*-1)){tLeft=element.oWidth*(pRatio-1)*-1;}
if(tTop<(element.oHeight*(pRatio-1)*-1)){tTop=element.oHeight*(pRatio-1)*-1;}
var attributes=new Array();attributes["tLeft"]=tLeft;attributes["tTop"]=tTop;attributes["tWidth"]=element.oWidth*pRatio;attributes["tHeight"]=element.oHeight*pRatio;attributes["duration"]=this.CYCLE_TIME*2;
this.animateElement(elementId,attributes);}}
AnimationController.prototype.showAndHide=function(elementId){
var element=document.getElementById(elementId);
if(element!=undefined){
if(element.style.display=="block"){this.hide(elementId);}else{this.show(elementId);}
}else{log.error("element '"+elementId+"' is undefined",this);}}
AnimationController.prototype.show=function(elementId){
var element=document.getElementById(elementId);
if(element!=undefined){element.style.display="block";element.state=this.STATE_ALTERNATE_ON;
var onComplete=(element.getAttribute("onOpen")!=undefined?element.getAttribute("onOpen"):(element.getAttribute("onopen")!=undefined?element.getAttribute("onopen"): element.onComplete));
if(onComplete!=undefined){eval(onComplete);}}}
AnimationController.prototype.hide=function(elementId){
var element=document.getElementById(elementId);
if(element!=undefined){element.style.display="none";element.state=this.STATE_ALTERNATE_OFF;
var onComplete=(element.getAttribute("onClose")!=undefined?element.getAttribute("onClose"):(element.getAttribute("onclose")!=undefined?element.getAttribute("onclose"): element.onComplete));
if(onComplete!=undefined){eval(onComplete);}}}
AnimationController.prototype.setOpacity=function(obj,opacity){
opacity=(opacity==100)?99.999:opacity;
if(obj!=undefined){
obj.style.filter="alpha(opacity:"+opacity+")";
obj.style.KHTMLOpacity=opacity/100;
obj.style.MozOpacity=opacity/100;
obj.style.opacity=opacity/100;}}
AnimationController.prototype.getOpacity=function(obj){
opacity=0;
if(obj!=undefined){if(obj.style.filter){var filterString=obj.style.filter;opacity=parseInt(filterString.match(/opacity\:([^\)].*)\)/)[1]);}else if(obj.style.KHTMLOpacity){opacity=parseInt(obj.style.KHTMLOpacity)*100;}else if(obj.style.MozOpacity){opacity=parseInt(obj.style.MozOpacity)*100;}else if(obj.style.opacity){opacity=parseInt(obj.style.opacity)*100;}}
return opacity;}
AnimationController.prototype.fade=function(elementId,sOpacity,tOpacity,onComplete,speed){
var attributes=new Array();attributes["sOpacity"]=sOpacity;attributes["tOpacity"]=tOpacity;attributes["duration"]=(speed!=undefined?speed : 300);attributes["onComplete"]=onComplete;
this.animateElement(elementId,attributes);}
AnimationController.prototype.fadeIn=function(elementId,onComplete,speed){
this.fade(elementId,0,100,onComplete,speed);}
AnimationController.prototype.fadeOut=function(elementId,onComplete,speed){
this.fade(elementId,100,0,onComplete,speed);}
AnimationController.prototype.startPulse=function(elementId,minimalOpacity,maximalOpacity,speed){
minimalOpacity=(minimalOpacity!=undefined?minimalOpacity : 30);maximalOpacity=(maximalOpacity!=undefined?maximalOpacity : 100);speed=(speed!=undefined?speed : this.CYCLE_TIME);
var element=document.getElementById(elementId);
if(element!=undefined){
var attributes=new Array();attributes["sOpacity"]=minimalOpacity;attributes["tOpacity"]=maximalOpacity;attributes["duration"]=speed;attributes["onComplete"]=this.id+".startPulse('"+elementId+"',"+maximalOpacity+","+minimalOpacity+","+speed+")";
this.animateElement(elementId,attributes);}}
AnimationController.prototype.stopPulse=function(elementId){
var element=document.getElementById(elementId);
if(element!=undefined){
element._onComplete=undefined;
if(element.thread!=undefined){clearTimeout(element.thread);element.thread=undefined;}
this.setOpacity(element,100);}}
AnimationController.prototype.setImage=function(elementId,imageUrl){
var element=document.getElementById(elementId);
if(element!=undefined){element.src=imageUrl;}}
var Anim=new AnimationController("Anim");
function AnimatorClass(id){
this.id=id;this.threadMap=new Array();this.scriptMap=new Array();
return this;}
AnimatorClass.prototype.threadMap=undefined;AnimatorClass.prototype.scriptMap=undefined;
AnimatorClass.prototype.runScriptId=function(scriptId){
if(this.scriptMap[scriptId]!=undefined){this.runScript(this.scriptMap[scriptId]);}}
AnimatorClass.prototype.runScript=function(script){
var jsScript="";var scriptId=script["id"];
this.stop(scriptId);this.register(scriptId,script);
threadArray=new Array();var storyboard=script["storyboard"];
for(timeStamp in storyboard){
jsScript="";for(taskIndex in storyboard[timeStamp]){jsScript+=(jsScript!=""?";" : "")+storyboard[timeStamp][taskIndex];}
threadArray.push(setTimeout(jsScript,timeStamp));}
this.threadMap[scriptId]=threadArray;}
AnimatorClass.prototype.stop=function(scriptId){
var threadArray=this.threadMap[scriptId];if(threadArray!=undefined){for(var index in threadArray){clearTimeout(threadArray[index]);}}
this.threadMap[scriptId]=undefined;}
AnimatorClass.prototype.register=function(scriptId,scriptInfo){
this.scriptMap[scriptId]=scriptInfo;}
var Animator=new AnimatorClass("Animator");
function DragDropController(id){
this.id=id;this.init();}
DragDropController.prototype.id="DragDropController";DragDropController.prototype.lastDraggedElementId=undefined;DragDropController.prototype.draggedElementIdList=undefined;DragDropController.prototype.dropZonesMap=undefined;
DragDropController.prototype.init=function(){
this.draggedElementIdList=new Array();this.dropZonesMap=new Array();
document.onmouseup=this._onMouseUp;document.onmousemove=this._onMouseMove;}
DragDropController.prototype._onMouseMove=function(e){
var element=undefined;var elementInfo=undefined;var newLeft=0;var newTop=0;
var mouseEvent=(e?e : event);
for(var elementId in DragDrop.draggedElementIdList){
elementInfo=DragDrop.draggedElementIdList[elementId];
if(elementInfo!=undefined){element=document.getElementById(elementId);
newLeft=(mouseEvent.clientX-elementInfo["left"]);newTop=(mouseEvent.clientY-elementInfo["top"]);
if(element._DDAttributes!=undefined){
if(element._DDAttributes["isVerticalOnly"]==true){newLeft=elementInfo["dragStartLeft"];}
if(element._DDAttributes["isHorizontalOnly"]==true){newTop=elementInfo["dragStartTop"];}
if(element._DDAttributes["isDiagonalX"]==true){newLeft=(newTop-element._DDAttributes["startTop"])+element._DDAttributes["startLeft"];}
if(element._DDAttributes["isDiagonalY"]==true){newTop=(newLeft-element._DDAttributes["startLeft"])+element._DDAttributes["startTop"];}
if(element._DDAttributes["limitX1"]!=undefined){newLeft=(newLeft>=element._DDAttributes["limitX1"]?newLeft : element._DDAttributes["limitX1"]);newLeft=(newLeft+parseInt(element.style.width)<=element._DDAttributes["limitX2"]?newLeft : element._DDAttributes["limitX2"]-parseInt(element.style.width));newTop=(newTop>=element._DDAttributes["limitY1"]?newTop : element._DDAttributes["limitY1"]);newTop=(newTop+parseInt(element.style.height)<=element._DDAttributes["limitY2"]?newTop : element._DDAttributes["limitY2"]-parseInt(element.style.height));}
if(element._DDAttributes["onDrag"]){eval(element._DDAttributes["onDrag"]);}}
var draggedElement=document.getElementById(element._DDAttributes["draggedElementId"]);
draggedElement.style.left=newLeft+"px";draggedElement.style.top=newTop+"px";}}
if(elementId!=undefined){
for(var zoneElementId in DragDrop.dropZonesMap){
zoneElement=document.getElementById(zoneElementId);
if(zoneElement!=undefined&&zoneElement._DDAttributes!=undefined){
if(zoneElement._DDAttributes["onDragOver"]!=undefined&&mouseEvent.clientX>getAbsLeft(zoneElement)&&mouseEvent.clientX<(getAbsLeft(zoneElement)+parseInt(zoneElement.style.width))&&mouseEvent.clientY>getAbsTop(zoneElement)&&mouseEvent.clientY<(getAbsTop(zoneElement)+parseInt(zoneElement.style.height))){
if(zoneElement._DDAttributes["isBeingDraggedOver"]==undefined){zoneElement._DDAttributes["isBeingDraggedOver"]=true;eval(zoneElement._DDAttributes["onDragOver"]);}
}else if(zoneElement._DDAttributes["isBeingDraggedOver"]!=undefined&&zoneElement._DDAttributes["onDragOut"]!=undefined){zoneElement._DDAttributes["isBeingDraggedOver"]=undefined;eval(zoneElement._DDAttributes["onDragOut"]);}}}}}
DragDropController.prototype._onMouseUp=function(e){
var mouseEvent=(e?e : event);
DragDrop.dropAll(mouseEvent);}
DragDropController.prototype.drag=function(mouseEvent,elementId){
var element=document.getElementById(elementId);
if(element!=undefined&&element._DDAttributes!=undefined&&element._DDAttributes["enabled"]){
this._deactivateMouseEvents();
this.lastDraggedElementId=element._DDAttributes["draggedElementId"];var draggedElement=document.getElementById(element._DDAttributes["draggedElementId"]);
if(element._DDAttributes["onPick"]){eval(element._DDAttributes["onPick"]);}
this.draggedElementIdList[elementId]={dragStartLeft:parseInt(draggedElement.offsetLeft),dragStartTop:parseInt(draggedElement.offsetTop),left:(mouseEvent.clientX-parseInt(draggedElement.offsetLeft)),top:(mouseEvent.clientY-parseInt(draggedElement.offsetTop))};
if(element._DDAttributes["isOnTopWhileDragging"]){element._DDAttributes["originalZIndex"]=draggedElement.style.zIndex+0;draggedElement.style.zIndex=999;}}}
DragDropController.prototype._deactivateMouseEvents=function(){
document.ondragstart=function(){return false;};
document.onselectstart=function(){return false;};}
DragDropController.prototype._activateMouseEvents=function(){
document.ondragstart=function(){return true;};
document.onselectstart=function(){return true;};}
DragDropController.prototype.drop=function(mouseEvent,elementId){
var element=document.getElementById(elementId);var draggedElement=document.getElementById(element._DDAttributes["draggedElementId"]);
if(element!=undefined&&element._DDAttributes!=undefined&&element._DDAttributes["enabled"]){
this._activateMouseEvents();
for(var zoneElementId in DragDrop.dropZonesMap){
zoneElement=document.getElementById(zoneElementId);
if(zoneElement!=undefined&&zoneElement._DDAttributes!=undefined){if(zoneElement._DDAttributes["onDropOver"]!=undefined&&mouseEvent.clientX>getAbsLeft(zoneElement)&&mouseEvent.clientX<(getAbsLeft(zoneElement)+parseInt(zoneElement.style.width))&&mouseEvent.clientY>getAbsTop(zoneElement)&&mouseEvent.clientY<(getAbsTop(zoneElement)+parseInt(zoneElement.style.height))){
if(zoneElement._DDAttributes["onDragOut"]!=undefined){eval(zoneElement._DDAttributes["onDragOut"]);}
eval(zoneElement._DDAttributes["onDropOver"]);}}}
if(element._DDAttributes["onDrop"]){eval(element._DDAttributes["onDrop"]);}
if(element._DDAttributes["isResetOnDrop"]==true){this.resetPosition(elementId);}
if(element._DDAttributes["isOnTopWhileDragging"]){draggedElement.style.zIndex=element._DDAttributes["originalZIndex"];}}
delete this.draggedElementIdList[elementId];}
DragDropController.prototype.dropAll=function(mouseEvent){
for(var elementId in this.draggedElementIdList){this.drop(mouseEvent,elementId);}
this.draggedElementIdList=new Array();}
DragDropController.prototype.resetPosition=function(elementId){
var element=document.getElementById(elementId);
if(element!=undefined&&element._DDAttributes!=undefined){Anim.animateElement(elementId,{tLeft:element._DDAttributes["startLeft"],tTop:element._DDAttributes["startTop"]});}}
DragDropController.prototype.setDropZone=function(elementId,attributes){
var element=document.getElementById(elementId);
if(element!=undefined){this.dropZonesMap[elementId]=true;element._DDAttributes=MapUtils.getClone(attributes);}}
DragDropController.prototype.isDraggeableElement=function(elementId){
var element=document.getElementById(elementId);
if(element!=undefined){return(element._DDAttributes!=undefined?true : false);}else{return false;}}
DragDropController.prototype.getElementAttributes=function(elementId){
var element=document.getElementById(elementId);
if(element!=undefined){return element._DDAttributes}else{return undefined;}}
DragDropController.prototype.doDrag=function(elementId,attributes){
var element=document.getElementById(elementId);var limitElement=undefined;
if(element!=undefined&&element._DDAttributes==undefined){
attributes=(attributes!=undefined?attributes : new Array());
element._DDAttributes=MapUtils.getClone(attributes);
if(attributes["draggedElementId"]==undefined){element._DDAttributes["draggedElementId"]=elementId;}
element._DDAttributes["enabled"]=true;element._DDAttributes["isOnTopWhileDragging"]=(attributes["isOnTopWhileDragging"]!=undefined?attributes["isOnTopWhileDragging"] : true);
var draggedElement=document.getElementById(element._DDAttributes["draggedElementId"]);
element._DDAttributes["startLeft"]=parseInt(draggedElement.offsetLeft);element._DDAttributes["startTop"]=parseInt(draggedElement.offsetTop);
if(attributes["limitElementId"]!=undefined){
limitElement=document.getElementById(attributes["limitElementId"]);
if(limitElement!=undefined){element._DDAttributes["limitX1"]=parseInt(limitElement.offsetLeft);element._DDAttributes["limitY1"]=parseInt(limitElement.offsetTop);element._DDAttributes["limitX2"]=parseInt(limitElement.offsetWidth)+element._DDAttributes["limitX1"];element._DDAttributes["limitY2"]=parseInt(limitElement.offsetHeight)+element._DDAttributes["limitY1"];}}
if(attributes["containerElementId"]!=undefined){
limitElement=document.getElementById(attributes["containerElementId"]);
if(limitElement!=undefined){element._DDAttributes["limitX1"]=0;element._DDAttributes["limitY1"]=0;element._DDAttributes["limitX2"]=parseInt(limitElement.offsetWidth);element._DDAttributes["limitY2"]=parseInt(limitElement.offsetHeight);}}
element.onmousedown=function(e){
DragDrop.drag((e?e : event),this.id);return false;}
element.onmouseup=function(e){
DragDrop.drop((e?e : event),this.id);return false;}}}
DragDropController.prototype.enable=function(elementId){
var element=document.getElementById(elementId);
if(element!=undefined&&element._DDAttributes!=undefined){element._DDAttributes["enabled"]=true;}}
DragDropController.prototype.disable=function(elementId){
var element=document.getElementById(elementId);
if(element!=undefined&&element._DDAttributes!=undefined){element._DDAttributes["enabled"]=false;}}
var DragDrop=new DragDropController("DragDrop");
function MessageController(id){this.id=id;}
MessageController.prototype.id="MessageController";MessageController.prototype.thrownErrorMessage=(typeof(errorMessage)!="undefined"?errorMessage : "");MessageController.prototype.messageObjectMap=undefined;MessageController.prototype.messageObjectCount=0;MessageController.prototype.calloutAttributes=undefined;MessageController.prototype.messageAttributes=undefined;MessageController.prototype.customAttributes=undefined;MessageController.prototype.defaultTemplate="<div style='border:1px solid black;background-color:white;left:0px;top:0px;width:220px;height:200px;' class='panel'><div style='left:20px;top:30px;width:165px;height:170px;overflow:auto;' class='label'>@message@</div></div>";
MessageController.prototype.X1=0;MessageController.prototype.Y1=1;MessageController.prototype.X2=2;MessageController.prototype.Y2=3;
MessageController.prototype.init=function(){
resource.applyProperties(this.id+"Properties",this);this.messageObjectMap=new Array();
if(this.thrownErrorMessage!=""){this.displayMessage({"message":this.thrownErrorMessage});}}
MessageController.prototype.initMessageObject=function(params){
var id=(params["messageObjectId"]!=undefined?params["messageObjectId"] : "messageObject"+this.messageObjectCount);
var messageObj=new MessageObject(id,this.id);
if(params["elementReference"]!=undefined){messageObj.elementReference=params["elementReference"];}
messageObj.duration=params["duration"];messageObj.width=params["width"];messageObj.height=params["height"];messageObj.isClosableOnClick=params["isClosableOnClick"];messageObj.heightAdjustment=params["heightAdjustment"]==undefined?0 : params["heightAdjustment"];
var position=undefined;
var backUrl=params["popupBackground"]==undefined?Workspace.message.messageAttributes["popupBackground"] : params["popupBackground"];
if(params["isForcedTopLeft"]&&(params["referenceBoundingBox"]==undefined&&params["elementReference"]==undefined)){position={"left":params["left"],"top":params["top"]};
}else if(params["referenceBoundingBox"]!=undefined){
position=this.getBestRelativePopupPosition(
params["referenceBoundingBox"],getElementBoundingBox(document.getElementById(params["containerSpace"])),messageObj.width,messageObj.height,messageObj.heightAdjustment);
if(position["isLeft"]){if(position["isTop"]){backUrl=params["popupImageBottomRight"];}else{backUrl=params["popupImageTopRight"];}}else{if(position["isTop"]){backUrl=params["popupImageBottomLeft"];}else{backUrl=params["popupImageTopLeft"];}}
}else if(params["elementReference"]!=undefined){
position=this.getBestRelativePopupPosition(
getElementBoundingBox(document.getElementById(params["elementReference"])),getElementBoundingBox(document.getElementById(params["containerSpace"])),messageObj.width,messageObj.height,messageObj.heightAdjustment);
if(position["isLeft"]){if(position["isTop"]){backUrl=params["popupImageBottomRight"];}else{backUrl=params["popupImageTopRight"];}}else{if(position["isTop"]){backUrl=params["popupImageBottomLeft"];}else{backUrl=params["popupImageTopLeft"];}}
}else if(document.getElementById(params["containerSpace"])!=undefined){position=this.getBestCenteredPopupPosition(getElementBoundingBox(document.getElementById(params["containerSpace"])));
}else{position={left:(Workspace.width-messageObj.width)/2,top:(Workspace.height-messageObj.height)/2};}
messageObj.background_url=backUrl;messageObj.left=position["left"];messageObj.top=position["top"];
messageObj.init();
this.messageObjectCount=this.messageObjectCount+1;this.messageObjectMap[messageObj.id]=messageObj;
return messageObj;}
MessageController.prototype.clearAll=function(){
for(var messageObjectId in this.messageObjectMap){this.hide(messageObjectId);}}
MessageController.prototype.displayMessage=function(params,type){
if(typeof(params)=="string"){if(params==""){return;}else{var temp=params;params=new Array();params["message"]=temp;}}
if(type!=undefined){if(this.customAttributes[type]!=undefined){params=MapUtils.putAll(this.customAttributes[type],params);}}
params["templateId"]=(params["templateId"]!=undefined?params["templateId"] : this.messageAttributes["templateId"]);params["heightAdjustment"]=0;
var messageWidth=undefined;var messageHeight=undefined;
if(document.getElementById(params["templateId"])!=null){messageWidth=(!isNaN(parseInt(document.getElementById(params["templateId"]).style.width))?parseInt(document.getElementById(params["templateId"]).style.width): this.messageAttributes["width"]);messageHeight=(!isNaN(parseInt(document.getElementById(params["templateId"]).style.height))?parseInt(document.getElementById(params["templateId"]).style.height): this.messageAttributes["height"]);
if(document.getElementById(params["templateId"]).heightAdjustment!=undefined){params["heightAdjustment"]=parseInt(document.getElementById(params["templateId"]).heightAdjustment);}}
else{messageWidth=this.messageAttributes["width"];messageHeight=this.messageAttributes["height"];}
params["left"]=(params["left"]!=undefined?params["left"] : this.messageAttributes["left"]);params["top"]=(params["top"]!=undefined?params["top"] : this.messageAttributes["top"]);params["width"]=(params["width"]!=undefined?params["width"] : messageWidth);params["height"]=(params["height"]!=undefined?params["height"] : messageHeight);params["duration"]=(params["duration"]!=undefined?params["duration"] : this.messageAttributes["duration"]);params["elementReference"]=(params["elementReference"]!=undefined?params["elementReference"] : this.calloutAttributes["elementReference"]);params["containerSpace"]=(params["containerSpace"]!=undefined?params["containerSpace"] : this.messageAttributes["containerSpace"]);params["isClosableOnClick"]=(params["isClosableOnClick"]!=undefined?params["isClosableOnClick"] : this.messageAttributes["isClosableOnClick"]);params["isForcedTopLeft"]=(params["isForcedTopLeft"]!=undefined?params["isForcedTopLeft"] : this.messageAttributes["isForcedTopLeft"]);
params["popupImageTopRight"]=(params["popupImageTopRight"]!=undefined?params["popupImageTopRight"] : this.calloutAttributes["popupImageTopRight"]);params["popupImageTopLeft"]=(params["popupImageTopLeft"]!=undefined?params["popupImageTopLeft"] : this.calloutAttributes["popupImageTopLeft"]);params["popupImageBottomRight"]=(params["popupImageBottomRight"]!=undefined?params["popupImageBottomRight"] : this.calloutAttributes["popupImageBottomRight"]);params["popupImageBottomLeft"]=(params["popupImageBottomLeft"]!=undefined?params["popupImageBottomLeft"] : this.calloutAttributes["popupImageBottomLeft"]);
params=MapUtils.putAll(params,params["attributes"]);params["attributes"]=undefined;
if(params["code"]!=undefined&&resource.get(code)!=""){message=resource.get(code);}else{if(params["message"]==undefined){message=this.messageAttributes["message"];}else{message=params["message"];}}
for(var messageId in this.messageObjectMap){if(messageId==params["messageObjectId"]){this.hide(messageId);break;}}
var newMessage=this.initMessageObject(params);params["messageObjectId"]=newMessage.id;
if(newMessage.elementId!=undefined){
params["message"]=message;params["background_url"]=newMessage.background_url;
newMessage.setContent(params["templateId"]!=undefined?params["templateId"] : this.defaultTemplate,params);
if(typeof(Anim)!="undefined"){Anim.setOpacity(document.getElementById(newMessage.elementId),0);newMessage.container.style.display="block";Anim.fadeIn(newMessage.elementId);newMessage.startThread();newMessage.isVisible=true;}else{document.getElementById(newMessage.elementId).style.display="block";}
return newMessage.id;}}
MessageController.prototype.hide=function(messageBoxId){
if(this.messageObjectMap[messageBoxId]!=undefined){
this.messageObjectMap[messageBoxId].isVisible=false;document.body.removeChild(this.messageObjectMap[messageBoxId].container);clearTimeout(this.messageObjectMap[messageBoxId].thread);delete this.messageObjectMap[messageBoxId];}}
MessageController.prototype.getBestCenteredPopupPosition=function(containerBoundingBox){
var popupWidth=parseInt(this.messageAttributes["width"]);var popupHeight=parseInt(this.messageAttributes["height"]);
var containerLeft=parseInt(containerBoundingBox[this.X1]);var containerTop=parseInt(containerBoundingBox[this.Y1]);var containerWidth=parseInt(containerBoundingBox[this.X2])-parseInt(containerBoundingBox[this.X1]);var containerHeight=parseInt(containerBoundingBox[this.Y2])-parseInt(containerBoundingBox[this.Y1]);
var top=containerTop+(containerHeight / 2)-(popupHeight / 2);var left=containerLeft+(containerWidth / 2)-(popupWidth / 2)
return{"left":left,"top":top};}
MessageController.prototype.getBestRelativePopupPosition=function(boundingBox,containerBoundingBox,popupWidth,popupHeight,heightAdjustment){
var distanceOfReference=0;
var popupLeft=0;var popupTop=0;
var scrollTop=parseInt(document.documentElement.scrollTop)* 2;var scrollLeft=parseInt(document.documentElement.scrollLeft)* 2;
var pageLayoutOffsetY=0;var pageLayoutOffsetX=0;
var containerLeft=parseInt(containerBoundingBox[this.X1])-pageLayoutOffsetX;var containerTop=parseInt(containerBoundingBox[this.Y1])-pageLayoutOffsetY;var containerWidth=parseInt(containerBoundingBox[this.X2])-containerBoundingBox[this.X1];var containerHeight=parseInt(containerBoundingBox[this.Y2])-containerBoundingBox[this.Y1];
var refLeft=parseInt(boundingBox[this.X1])+containerLeft;var refTop=parseInt(boundingBox[this.Y1])+containerTop;var refWidth=parseInt(boundingBox[this.X2])-boundingBox[this.X1];var refHeight=parseInt(boundingBox[this.Y2])-boundingBox[this.Y1];
var leftPosition=parseInt(refLeft)-parseInt(distanceOfReference)-parseInt(popupWidth)+parseInt(scrollLeft);var rightPosition=parseInt(refLeft)+parseInt(refWidth)+parseInt(distanceOfReference)+parseInt(scrollLeft);
var topPosition=parseInt(refTop)+parseInt(refHeight)-parseInt(popupHeight)+parseInt(scrollTop)-parseInt(heightAdjustment);var bottomPosition=parseInt(refTop)+parseInt(scrollTop)+parseInt(heightAdjustment);
var isLeft=true;var isTop=true;
var positionInfo=new Array();
if(refTop>(containerHeight-refTop-refHeight)){positionInfo["top"]=topPosition;positionInfo["isTop"]=true;}
else{positionInfo["top"]=bottomPosition;positionInfo["isTop"]=false;}
if(refLeft>(containerWidth-refLeft-refWidth)){positionInfo["left"]=leftPosition;positionInfo["isLeft"]=true;}
else{positionInfo["left"]=rightPosition;positionInfo["isLeft"]=false;}
return positionInfo;
}
MessageController.prototype.isCursorOver=function(messageId,pX,pY){
var returnValue=false;
if(this.messageObjectMap[messageId]!=undefined){
var calloutElement=this.messageObjectMap[messageId].container;
if(calloutElement!=undefined){
var calloutX1=getAbsLeft(calloutElement)-20;var calloutY1=getAbsTop(calloutElement)-20;var calloutX2=calloutX1+parseInt(calloutElement.style.width)+40;var calloutY2=calloutY1+parseInt(calloutElement.style.height)+40;
if(pX>=calloutX1&&pY>=calloutY1&&pX<=calloutX2&&pY<=calloutY2){returnValue=true;}}}
return returnValue;}
function MessageObject(id,parentController){
this.id=id;this.elementId=id;this.parentController=parentController;}
MessageObject.prototype.X1=0;MessageObject.prototype.Y1=1;MessageObject.prototype.X2=2;MessageObject.prototype.Y2=3;
MessageObject.prototype.id="MessageObject";MessageObject.prototype.elementId="";MessageObject.prototype.backgroundElementId="";MessageObject.prototype.contentElementId="";MessageObject.prototype.elementReference="pageLayout";MessageObject.prototype.parentController="Workspace.message";MessageObject.prototype.duration=0;MessageObject.prototype.top=undefined;MessageObject.prototype.left=undefined;MessageObject.prototype.width=undefined;MessageObject.prototype.height=undefined;MessageObject.prototype.background_url="";MessageObject.prototype.popupImageTopLeft=undefined;MessageObject.prototype.popupImageTopRight=undefined;MessageObject.prototype.popupImageBottomLeft=undefined;MessageObject.prototype.popupImageBottomRight=undefined;MessageObject.prototype.imageTopLeft="popupImageTopLeft";MessageObject.prototype.imageTopRight="popupImageTopRight";MessageObject.prototype.imageBottomLeft="popupImageBottomLeft";MessageObject.prototype.imageBottomRight="popupImageBottomRight";MessageObject.prototype.isInitialized=false;MessageObject.prototype.isVisible=false;MessageObject.prototype.isFadeInEffectActive=true;MessageObject.prototype.targetFadePercentage=100;
MessageObject.prototype.thread=undefined;MessageObject.prototype.isClosableOnClick=true;MessageObject.prototype.heightAdjustment=0;
MessageObject.prototype.init=function(){
this.container=this.createContainer(this.left,this.top,this.width,this.height,this.isClosableOnClick);this.isInitialized=true;}
MessageObject.prototype.startThread=function(){
if(this.duration!=0){this.thread=setTimeout(this.parentController+".hide('"+this.id+"')",this.duration);}}
MessageObject.prototype.setContent=function(templateElementId,attributes){
ParserUtils.applyTemplate(templateElementId,this.container.id,attributes);}
MessageObject.prototype.hide=function(){
Workspace.message.hide(this.id);}
MessageObject.prototype.createContainer=function(left,top,width,height,isClosableOnClick){
var newdiv=document.createElement('div');
newdiv.setAttribute('id',this.elementId);
if(isClosableOnClick){newdiv.onclick=new Function("Workspace.message.hide('"+this.elementId+"')");}
newdiv.style.position="absolute";
if(width){newdiv.style.width=width+"px";}
if(height){newdiv.style.height=height+"px";}
if(left){newdiv.style.left=left+"px";}
if(top){newdiv.style.top=top+"px";}
newdiv.style.display="none";document.body.appendChild(newdiv);
return newdiv;}
function WindowController(id,attributes){
this.id=id;this.setAttributes(attributes);this.registerEventListeners();
this.init();}
WindowController.prototype.id="WindowController";WindowController.prototype.element=undefined;WindowController.prototype.attributes=undefined;WindowController.prototype.isMinimized=false;WindowController.prototype.isMaximized=false;WindowController.prototype.state="";WindowController.prototype.isVisible=false;WindowController.prototype.isGenerated=false;WindowController.prototype.isExtended=false;WindowController.prototype.eventListenerMap=undefined;
WindowController.prototype.WINDOW_NORMAL="WINDOW_NORMAL";WindowController.prototype.WINDOW_MAXIMIZED="WINDOW_MAXIMIZED";WindowController.prototype.WINDOW_MINIMIZED="WINDOW_MINIMIZED";WindowController.prototype.WINDOW_HIDDEN="WINDOW_HIDDEN";
WindowController.prototype.WINDOW_STYLE_DHTML="DHTML";WindowController.prototype.WINDOW_STYLE_POPUP="POPUP";
WindowController.prototype.EVENT_ACTION_REFRESH=0;WindowController.prototype.EVENT_ACTION_SHOW=1;WindowController.prototype.EVENT_ACTION_HIDE=2;
WindowController.prototype.init=function(isForced){
isForced=(isForced==undefined?false : isForced);
if(this.attributes["autoShow"]||isForced){
if(this.attributes["controller"]!=""){
if(Workspace.isInitialized){Workspace.activateController(this.attributes["controller"],undefined,this.id+".generate()");}else{loopUntil("Workspace.isInitialized",this.id+".init()");}}else{this.generate();}}}
WindowController.prototype.registerEventListeners=function(){
this.eventListenerMap=new Array();
this._registerEventList(this.attributes["showOnEvents"],this.EVENT_ACTION_SHOW);this._registerEventList(this.attributes["hideOnEvents"],this.EVENT_ACTION_HIDE);this._registerEventList(this.attributes["refreshOnEvents"],this.EVENT_ACTION_REFRESH);}
WindowController.prototype._registerEventList=function(eventList,action){
this.eventListenerMap[action]=new Array();
for(var i=0;i<eventList.length;i++){
this.eventListenerMap[action][eventList[i]]=action;Workspace.events.addListener(eventList[i],this);}}
WindowController.prototype.setAttributes=function(attributes){
this.attributes={"controllerId":this.id,"elementId":this.id+"Window","style":this.WINDOW_STYLE_DHTML,"autoShow":false,"onShow":"","onHide":"","onGenerate":"","left":0,"top":0,"width":400,"height":400,"class":"window","isDraggable":false,"isControlBar":false,"templateId":"","content":"","contentUrl":"","frameUrl":"","title":"","initialWindowState":this.WINDOW_NORMAL,"controller":"","refreshOnEvents":new Array(),"showOnEvents":new Array(),"hideOnEvents":new Array()}
this.attributes=MapUtils.putAll(this.attributes,attributes);}
WindowController.prototype.generate=function(){
if(!this.isGenerated){
Workspace.events.addListener(Workspace.events.EVENT_WINDOW_GENERATE,this);Workspace.events.addListener(Workspace.events.EVENT_WINDOW_SHOW,this);Workspace.events.addListener(Workspace.events.EVENT_WINDOW_HIDE,this);
if(this.attributes["style"]==this.WINDOW_STYLE_DHTML){this._generateDhtmlWindow();}else if(this.attributes["style"]==this.WINDOW_STYLE_POPUP){this._generatePopupWindow();}
this.isGenerated=true;
}else if(this.attributes["style"]==this.WINDOW_STYLE_POPUP&&this.element.closed){this._generatePopupWindow();
}else{this._generateContent();}}
WindowController.prototype._generateDhtmlWindow=function(){
this.element=document.getElementById(this.attributes["elementId"]);
if(this.element==undefined){
this.element=document.createElement("DIV");this.element.id=this.id+"Window";
this.element.style.left=this.attributes["left"]+"px";this.element.style.top=this.attributes["top"]+"px";this.element.style.width=this.attributes["width"]+"px";this.element.style.height=this.attributes["height"]+"px";
if(this.attributes["isControlBar"]){this.element.className=this.attributes["class"];}
getE("pageLayout").appendChild(this.element);}
this.element.innerHTML=
(this.attributes["isControlBar"]?
"<div class='windowControlBar' id='"+this.id+"ControlBar' ondblclick='"+this.id+".controlBarDoubleClick()'>"+(this.attributes["title"]!=""?"<span class='windowTitle'>"+this.attributes["title"]+"</span>" : "")+"<div onclick='"+this.id+".minimize()' class='windowControlButton'>_</div>"+"<div onclick='"+this.id+".maximize()' class='windowControlButton'>[]</div>"+"<div onclick='"+this.id+".hide()' class='windowControlButton'>X</div>"+"</div>"
: "")
+"<div id='"+this.id+"Container' class='windowContainer'></div>";+(this.attributes["isControlBar"]?"<img id='"+this.id+"Scale' src='/images/windowscale.gif' class='windowScaler'/>" : "");
if(this.attributes["isDraggable"]){DragDrop.doDrag(this.id+"ControlBar",{"draggedElementId":this.id+"Window","onPick":this.id+"._onPick()","onDrop":this.id+"._onDragComplete()"});DragDrop.doDrag(this.id+"Scale",{"onDrag":this.id+"._onScale()","onDrop":this.id+"._onScaleComplete()"});}
this._generateContent();
this.attributes["left"]=getAbsLeft(this.element);this.attributes["top"]=getAbsTop(this.element);this.attributes["width"]=getWidth(this.element);this.attributes["height"]=getHeight(this.element);}
WindowController.prototype._generatePopupWindow=function(){
this.element=window.open("",this.id+"Window",(this.attributes["width"]!=""?"width="+this.attributes["width"] : "")+(this.attributes["height"]!=""?",height="+this.attributes["height"] : "")+(this.attributes["isControlBar"]?",status=no,menubar=no,toolbar=no,resizable=no" : ",status=yes,menubar=no,toolbar=no,resizable=no")+",scrollbars=1");this.element.focus();
this._generateContent();}
WindowController.prototype.refresh=function(){
this._generateContent();}
WindowController.prototype._generateContent=function(){
if(this.attributes["content"]!=""){this.setContent(this.attributes["content"]);}
if(this.attributes["templateId"]!=""){this.applyTemplate(this.attributes["templateId"]);}
if(this.attributes["contentUrl"]!=""){this.loadContentFromUrl(this.attributes["contentUrl"]);}
if(this.attributes["frameUrl"]!=""){this.loadUrl(this.attributes["frameUrl"]);}}
WindowController.prototype.setContent=function(content){
if(this.attributes["style"]==this.WINDOW_STYLE_DHTML){document.getElementById(this.id+"Container").innerHTML=content;}else if(this.attributes["style"]==this.WINDOW_STYLE_POPUP){
if(this.element==undefined||this.element.closed){this._generatePopupWindow();}
this.element.document.open("text/html","replace");this.element.document.write(content);this.element.document.close();}
Workspace.events.throwEvent(Workspace.events.EVENT_WINDOW_GENERATE,this);}
WindowController.prototype.applyTemplate=function(templateId){
ParserUtils.preloadTemplate(templateId,this.id+".setContent(ParserUtils.parseTemplate('"+templateId+"'," +this.id+".attributes))");}
WindowController.prototype.loadContentFromUrl=function(url){
if(this.attributes["style"]==this.WINDOW_STYLE_DHTML){
if(typeof(Workspace)!="undefined"&&Workspace.events!=undefined&&!Workspace.events.isEventListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this)){Workspace.events.addListener(Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED,this);}
this._sendRequest(url);}else if(this.attributes["style"]==this.WINDOW_STYLE_POPUP){
if(this.element==undefined||this.element.closed){this._generatePopupWindow();}
this.loadUrl(url);}}
WindowController.prototype.loadUrl=function(url){
if(this.attributes["style"]==this.WINDOW_STYLE_DHTML){
log.debug("loading frame url:"+url,this);
if(document.getElementById(this.id+"Iframe")==undefined){this.setContent("<iframe id='"+this.id+"Iframe' style='position:absolute;left:0px;top:0px;width:100%;height:100%;' frameborder='0' src='"+url+"'></iframe>");}else{document.getElementById(this.id+"Iframe").src=url;}
}else if(this.attributes["style"]==this.WINDOW_STYLE_POPUP){
if(this.element==undefined||this.element.closed){this._generatePopupWindow();}
this.element.location=url;}
Workspace.events.throwEvent(Workspace.events.EVENT_WINDOW_GENERATE,this);}
WindowController.prototype._onPick=function(){}
WindowController.prototype._onScale=function(){
var scaleElement=document.getElementById(this.id+"Scale");
var newWidth=getAbsLeft(scaleElement)-getAbsLeft(this.element)+20;var newHeight=getAbsTop(scaleElement)-getAbsTop(this.element)+20;
newWidth=(newWidth>140?newWidth : 140);newHeight=(newHeight>20?newHeight : 20);
this.element.style.width=newWidth+"px";this.element.style.height=newHeight+"px";}
WindowController.prototype._onScaleComplete=function(){
var scaleElement=document.getElementById(this.id+"Scale");
this.attributes["width"]=(parseInt(scaleElement.style.left)+20);this.attributes["height"]=(parseInt(scaleElement.style.top)+20);}
WindowController.prototype._onDragComplete=function(){
this.attributes["left"]=getAbsLeft(this.element);this.attributes["top"]=getAbsTop(this.element);}
WindowController.prototype.minimize=function(){
if(this.isMaximized){this.restore();
}else{DragDrop.disable(this.id+"ControlBar");DragDrop.disable(this.id+"Scale");
this.attributes["left"]=getAbsLeft(this.element);this.attributes["top"]=getAbsTop(this.element);
this.isMinimized=true;this.isMaximized=false;
Anim.animateElement(this.id+"Window",{tLeft:0,tTop:600,tWidth:200,tHeight:20});}}
WindowController.prototype.restore=function(){
DragDrop.enable(this.id+"ControlBar");DragDrop.enable(this.id+"Scale");
Anim.animateElement(this.id+"Window",{"tLeft":this.attributes["left"],"tTop":this.attributes["top"],"tWidth":this.attributes["width"],"tHeight":this.attributes["height"]});
this.isMinimized=false;this.isMaximized=false;}
WindowController.prototype.maximize=function(){
if(this.isMinimized){this.restore();
}else{DragDrop.disable(this.id+"ControlBar");DragDrop.disable(this.id+"Scale");
Anim.animateElement(this.id+"Window",{"tLeft":0,"tTop":0,"tWidth":Workspace.width,"tHeight":Workspace.height});
this.isMinimized=false;this.isMaximized=true;}}
WindowController.prototype.controlBarDoubleClick=function(){
if(this.isMinimized||this.isMaximized){this.restore();}else{this.maximize();}}
WindowController.prototype.hide=function(){
this.isVisible=false;
if(this.isGenerated&&this.attributes["style"]==this.WINDOW_STYLE_DHTML){
Anim.fadeOut(this.element.id,"document.getElementById('"+this.element.id+"').style.display='none';");}else if(this.isGenerated&&this.attributes["style"]==this.WINDOW_STYLE_POPUP){
this.element.close();}
Workspace.events.throwEvent(Workspace.events.EVENT_WINDOW_HIDE,this);}
WindowController.prototype.show=function(){
this.isVisible=true;
if(!this.isGenerated){this.init(true);}else{if(this.attributes["style"]==this.WINDOW_STYLE_DHTML){this.element.style.display="block";Anim.fadeIn(this.element.id);}else if(this.attributes["style"]==this.WINDOW_STYLE_POPUP&&this.element==undefined||this.element.closed){this._generatePopupWindow();}
this.refresh();}
Workspace.events.throwEvent(Workspace.events.EVENT_WINDOW_SHOW,this);}
WindowController.prototype.toggle=function(){
if(this.isVisible){this.hide();}else{this.show();}}
WindowController.prototype._sendRequest=function(action,infoMap){
det.sendRequest({method:"GET",responseFormat:det.RESPONSE_FORMAT_TEXT,serverUrl:action,action:action,info:infoMap,timeout:5000,callingController:this});}
WindowController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_SERVER_RESPONSE_RECEIVED&&attributes.callingController==this&&attributes!=undefined&&attributes.response!=undefined){
if(attributes.error!=undefined){this.setContent("Request timed out.");}else{this.setContent(attributes.response["textResponse"]);}
}else if(this.isVisible&&this.eventListenerMap[this.EVENT_ACTION_REFRESH][eventKey]!=undefined){this.refresh();}else if(this.eventListenerMap[this.EVENT_ACTION_SHOW][eventKey]!=undefined){this.show();}else if(this.eventListenerMap[this.EVENT_ACTION_HIDE][eventKey]!=undefined){this.hide();}
if(attributes==this){
if(eventKey==Workspace.events.EVENT_WINDOW_INIT&&this.attributes["onInit"]!=""){eval(this.attributes["onInit"]);}else if(eventKey==Workspace.events.EVENT_WINDOW_GENERATE&&this.attributes["onGenerate"]!=""){eval(this.attributes["onGenerate"]);}else if(eventKey==Workspace.events.EVENT_WINDOW_SHOW&&this.attributes["onShow"]!=""){eval(this.attributes["onShow"]);}else if(eventKey==Workspace.events.EVENT_WINDOW_HIDE&&this.attributes["onHide"]!=""){eval(this.attributes["onHide"]);}}}
function RemoteController(id){
this.id=id;}
RemoteController.prototype.id="RemoteController";RemoteController.prototype._communicationUrl="";RemoteController.prototype.eventListeners=undefined;
RemoteController.prototype.init=function(){
resource.applyProperties(this.id+"Properties",this);
Workspace.events.addListener(Workspace.events.EVENT_PAGE_LOADED,this);Workspace.events.addListener(Workspace.events.EVENT_COOKIE_CHANGED,this);
Workspace.events.throwEvent(Workspace.events.EVENT_CONTROLLER_INITIALIZED,this);
if(this.eventListeners!=undefined){for(var eventName in this.eventListeners){Workspace.events.addListener(eventName,this);}}}
RemoteController.prototype.registerRemote=function(url){
this._communicationUrl=url;}
RemoteController.prototype.getRemoteAction=function(){
if(document.cookie.indexOf("mvmRemoteAction")>-1){
var remoteAction=CookieUtils.getAttribute("mvmRemoteAction");
CookieUtils.deleteCookie("mvmRemoteAction");
return remoteAction;}else{return undefined;}}
RemoteController.prototype.handleRemoteAction=function(){
var remoteAction=this.getRemoteAction();
if(remoteAction!=undefined){
try{
eval(decodeURIComponent(remoteAction));}catch(e){log.error("could not execute remote action: "+remoteAction+" Cause : "+e.message);}}}
RemoteController.prototype.throwEvent=function(eventKey){
Workspace.events.throwEvent(eventKey,this);}
RemoteController.prototype.call=function(action){
if(this._communicationUrl!=""){parent.location=this._communicationUrl+"#mvmaction="+encodeURIComponent(action);}}
RemoteController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_COOKIE_CHANGED||eventKey==Workspace.events.EVENT_PAGE_LOADED){
if(document.cookie.indexOf("mvmRemoteAction")>-1){this.handleRemoteAction();}}
if(this.eventListeners!=undefined&&this.eventListeners[eventKey]!=undefined){this.call(eventKey+"|"+ParserUtils.parseHtml(this.eventListeners[eventKey]));}}
function WeightlossWindowController(id,attributes){jsClass.extend(this,[WindowController]);
this.id=id;this.setAttributes(attributes);this.registerEventListeners();
this.attributes["onGenerate"]=this.id+".refresh()";
this.init();}
WeightlossWindowController.prototype.id="WeightlossWindowController";WeightlossWindowController.prototype.viewId=1;WeightlossWindowController.prototype.fieldObjectMap=undefined;WeightlossWindowController.prototype.answerMap=undefined
WeightlossWindowController.prototype.isFieldsGenerated=false;WeightlossWindowController.prototype.callout=undefined;WeightlossWindowController.prototype.isForceLowerGoalWeight=true;WeightlossWindowController.prototype.isWarnUserForIncompatibleGarments=true;WeightlossWindowController.prototype.MIN_BMI_VALUE=18;
WeightlossWindowController.prototype.registerEventListeners=function(){
Workspace.events.addListener(Workspace.events.EVENT_MODEL_CONTENT_CHANGED,this);Workspace.events.addListener(Workspace.events.EVENT_INCOMPATIBLE_ITEM_REMOVED,this);Workspace.events.addListener(Workspace.events.EVENT_MODEL_ATTRIBUTES_CHANGED,this);
this.super_WindowController_registerEventListeners();}
WeightlossWindowController.prototype.show=function(){
if(Workspace.user.isSignedIn&&!Workspace.user.isAuthenticated){Workspace.events.addListener(Workspace.events.EVENT_USER_AUTHENTICATED,this);Workspace.user.displayAuthentication();}else{
this.super_WindowController_show();
loopUntil(this.id+".fieldObjectMap!=undefined",this.id+".updateWeights()");}}
WeightlossWindowController.prototype.getMetricHeightValue=function(){
if(ModelQuestionnaire.heightMappedBMIArray!=undefined&&ModelQuestionnaire.fieldObjectMap!=undefined&&ModelQuestionnaire.fieldObjectMap["Height"]!=undefined){
return ModelQuestionnaire.heightMappedBMIArray[ModelQuestionnaire.fieldObjectMap["Height"].getValue()];}}
WeightlossWindowController.prototype.rotateLeft=function(){
this.viewId=(this.viewId+1>Model.viewCount[Model.layoutId]?1 : this.viewId+1);this.refresh();}
WeightlossWindowController.prototype.rotateRight=function(){
this.viewId=(this.viewId-1<1?Model.viewCount[Model.layoutId] : this.viewId-1);this.refresh();}
WeightlossWindowController.prototype.updateModel=function(){
if(getE("ModelWeightlossImage")!=undefined){
var answersMap=this.getModelAttributes();
Model.requestModelInfo(undefined,{"imageElementId":"ModelWeightlossImage" ,"appearanceAnswers":"WeightNum="+answersMap["WeightGoal"],"viewId":this.viewId});}}
WeightlossWindowController.prototype.setUnitSystem=function(unitSystem){
FieldUtils.setAllFieldsUnitSystem(this.fieldObjectMap,unitSystem,this);}
WeightlossWindowController.prototype.updateWeights=function(){
if(this.validateWeights()){
ModelQuestionnaire.setAnswersMap({'WeightNum':this.fieldObjectMap["WeightNum"].getValue(),'WeightGoal':this.fieldObjectMap["WeightGoal"].getValue()},true);}}
WeightlossWindowController.prototype.validateWeights=function(){
var returnValue=false;
if(this.isForceLowerGoalWeight&&(this.fieldObjectMap==undefined||
this.fieldObjectMap["WeightGoal"]==undefined&&this.fieldObjectMap["WeightNum"]==undefined)){
var answersMap=this.getModelAttributes();
if(answersMap["WeightGoal"]>answersMap["WeightNum"]){Workspace.message.displayMessage(resource.get("Weightloss.InvalidGoalWeight"));returnValue=false;}else{returnValue=true;}
}else if(this.isForceLowerGoalWeight&&this.fieldObjectMap!=undefined&&parseInt(this.fieldObjectMap["WeightGoal"].getValue())>parseInt(this.fieldObjectMap["WeightNum"].getValue())){
Workspace.message.displayMessage(resource.get("Weightloss.InvalidGoalWeight"));returnValue=false;
}else if(this.fieldObjectMap!=undefined&&this.fieldObjectMap["WeightNum"].isValid()==FieldUtils.FIELD_VALID&&this.fieldObjectMap["WeightGoal"].isValid()==FieldUtils.FIELD_VALID){
returnValue=true;}
return returnValue;}
WeightlossWindowController.prototype.onFieldFocus=function(fieldObject){
Workspace.message.hide(this.callout);
if(fieldObject.state!=fieldObject.FIELD_VALID&&fieldObject.isChanged()){var attributes=new Array();attributes["message"]=fieldObject.getErrorMessage();attributes["templateId"]="calloutTemplate";attributes["elementReference"]=this.id+"_"+fieldObject.name;attributes["duration"]=5000;attributes["messageObjectId"]="fieldValidation";
if(fieldObject.isValid()!=FieldUtils.FIELD_VALID){this.callout=Workspace.message.displayMessage(attributes);}else{Workspace.message.hide(this.callout);}}}
WeightlossWindowController.prototype.onFieldBlur=function(fieldObject){
Workspace.message.hide(this.callout);}
WeightlossWindowController.prototype.getModelAttributes=function(){
var answersMap=ModelQuestionnaire.getAnswersMap();
answersMap["WeightGoal"]=(answersMap["WeightGoal"]!=undefined?answersMap["WeightGoal"] : answersMap["WeightNum"]);
return answersMap;}
WeightlossWindowController.prototype.refresh=function(){
var answersMap=this.getModelAttributes();
if(!this.isFieldsGenerated){
this.answerMap={"WeightNum":answersMap["WeightNum"],"WeightGoal":answersMap["WeightGoal"]}
this.fieldObjectMap=FieldUtils.initFieldsList(
this.answerMap,this,this.id);
this.isFieldsGenerated=true;}else{this.fieldObjectMap["WeightNum"].value=answersMap["WeightNum"];this.fieldObjectMap["WeightGoal"].value=answersMap["WeightGoal"];this.fieldObjectMap["WeightNum"].generate();this.fieldObjectMap["WeightGoal"].generate();
}
this.updateModel();}
WeightlossWindowController.prototype.setUnitSystem=function(unitSystem){
FieldUtils.setAllFieldsUnitSystem(this.fieldObjectMap,unitSystem,this);}
WeightlossWindowController.prototype.catchEvent=function(eventKey,attributes){
if(eventKey==Workspace.events.EVENT_USER_AUTHENTICATED){this.show();}
this.super_WindowController_catchEvent(eventKey,attributes);}
