//--------------------------------------------------------------------------------------CardsGlobal
 
var CardsGlobal = Class.create({
    /*this is to hold the user selected data and to track the actions if any
    - these are all class level static values */
 
    selectedSku : undefined,
    selectedPhotoCount : undefined,
    selectedCategory : undefined,
    selectedParentCategory : undefined,
    selectedSubCategory : undefined,
    selectedTheme : undefined,
    selectedLayout: undefined,
    selectedPaper : undefined,
    selectedOrientation : undefined,
 
    cardDesignsJsonDataObj : undefined,
    cardDesignsObj : undefined,
    cardLayoutsObj : undefined,
 
    themeLayoutsMap : new Hash(),
    themeLayoutsJsonMap : new Hash(),
 
    // page related variables
    isCardsdesignsSubscribed : false,
    isCardsLayoutsSubscribed : false,
    onClickX:0, /*these will store the mouse click event locations captured by captureOnClickEvent() function */
    onClickY:0,
    hasFeatured:false,
    isStationery:false
});
var cardsGlobal = new CardsGlobal();
 
//--------------------------------------------------------------------------------------CCardsDesigns
 
//CCardsDesigns would have all the data needed for the cards selector page
// filtering happens on the client, since it is just a 2 while loops to get the data out.
var CCardsDesigns = Class.create({
 
    initialize : function(designsJson){
        this.m_skus = Vector.getInstance();
      this.m_defaultSku = null;
      this.m_skuMap = Hashtable.getInstance();
      this.m_photoFilters = undefined;
      this.m_defaultPhotoFilter = "all";
      this.m_defaultCategory = undefined;
      this.m_defaultCategoryDisplayName = undefined;
      this.m_themeCountToShow=12;
      this.m_orientationBySkuMap = Hashtable.getInstance();
      this.m_moreLimit=10;

      this.fillValue(designsJson);
    },
 
  fillValue : function(designsJson)
  {
    // just fill the data
    var _skus = designsJson.skus ;
 
    if(designsJson.morelimit)
        this.m_moreLimit = designsJson.morelimit;
    if(_websiteInfo.getRegion() == 'snapfish_eu' && _websiteInfo.getWebsiteName()!= 'snapfish_uk')
        this.m_moreLimit = 15;
 
    //alert(_skus.length);
    var skuObj = null;
    for(var counter=0;counter<_skus.length;counter++)
    {
      skuObj = _skus[counter];
      this.m_skus.add(skuObj.sku) ;
      //var skuCategoriesData = designsJson[sku];// eval('designsJson.'+(sku.replace(" ", "\ ")))  ;
      var skuCategoriesData = designsJson.categories;
 
      if(!skuCategoriesData) continue;
 
      //this.m_skuMap.put(sku , (new CCategories(skuCategoriesData)));
      this.m_skuMap.put(skuObj.sku , (new CCategories(designsJson, skuObj, false)));
 
      //this.m_orientationBySkuMap.put(sku, designsJson.orientationbysku[sku]);
      this.m_orientationBySkuMap.put(skuObj.sku, skuObj.defaultorientation);
    }// end of for
 
    if(_skus.length > 1){
        this.m_skuMap.put("all", (new CCategories(designsJson, _skus[0], true)));
        this.m_orientationBySkuMap.put("all", _skus[0].defaultorientation);
    }
 
    this.m_defaultSku = _skus[0].sku;//designsJson.defaultsku ;
    if(designsJson.filterkeys)
    {
      this.m_photoFilters = Hashtable.getInstance() ;
      for(var i=0;i<designsJson.filterkeys.length;i++)
      {
        var key = designsJson.filterkeys[i];
        var value = designsJson.filtervalues[i];
        this.m_photoFilters.put(key, value);
      }
    }
 
        this.m_defaultCategory = this.getSkuMap().get(this.m_defaultSku).getCategories().keys().nextElement();
        var categories1 = this.getSkuMap().get(this.m_defaultSku).getCategories();
        var oCategory1 = categories1.get(this.m_defaultCategory) ;
        this.m_defaultCategoryDisplayName = oCategory1.getDisplayName();
  } ,
  filterCategory : function(categoryName, sku, photoFilter, categoryParentName,orientation /*optional*/)
  {
    /*
      1)   first try to filter the values of by sku, if sku is null get the card designs default sku and filter it
          a) for example, if at all user selects 4x8 get 4x8 categories and then get the category selected, then do the filtering by photoFilter
          b) in case if user selects 'all sizes' then get the default sku, and get the selected category and then filter by photoFilter,
            but we do need to maintain a seperate a flag for this case for each theme that is filetered out by that sku, which doesnt exist in the other sku.
            we still need to display them.
      2) At the end of the above step we should be ending with a bunch of themes that needed to be rendered.
      3) Now, filter them out by photoFileter, if the value is 'all' just return it.
        Else filter them themes using mincount and max count of the them with photoFilter
 
    */
    console.debug("Filter Parameter; "+ categoryName +","+ sku+","+ photoFilter+","+categoryParentName+","+orientation);
 
    var themeMap = Hashtable.getInstance() ;
 
    if(categoryName == undefined || sku == undefined || photoFilter == undefined) return themeMap;
 
    var categories = this.getSkuMap().get(sku).getCategories();
        var oCategory = categories.get(categoryName) ;
    if(oCategory == null || oCategory == undefined)
    {
        /*if category is null means its subcategory so take parentcategory*/
        if(categoryParentName)
        {
            oCategory = categories.get(categoryParentName);
            if(oCategory)
            {
                oCategory = oCategory.getSubCategories().get(categoryName);
            }
        }
    }else
    {
        /*This case will arise when default category has sub categories*/
        if(oCategory.hasSubCategories())
        {
            cardsGlobal.selectedParentCategory = oCategory.getName();
            oCategory = oCategory.getSubCategories().get(oCategory.getSubCategories().keys().nextElement());
            cardsGlobal.selectedCategory = oCategory.getName();
        }
    }
    if(!oCategory || oCategory == "null")
    {
        var catKeys = categories.keys();
        if(catKeys.hasMoreElements())
            categoryName =  catKeys.nextElement();
        oCategory = categories.get(categoryName); // if the given category is not found for this sku
    }
        var themeKeys = oCategory.getThemes().keys() ;
        console.debug("Filtering by orientation="+orientation);
        while(themeKeys.hasMoreElements())
        {
          var themeKey = themeKeys.nextElement() ;
          var oTheme = oCategory.getThemes().get(themeKey) ;
          var orientationMap=null;
          var orientationConstraintSatisfied=true;
          if(typeof orientation != 'undefined'){
              var iconURL=oTheme.getThemeIconUrl(sku,orientation,photoFilter,true);
              if(iconURL == null || iconURL == 'undefined' || iconURL == '')
              orientationConstraintSatisfied=false;
          }
          if(this.m_defaultPhotoFilter == photoFilter && orientationConstraintSatisfied)
          {
            if(!themeMap.get(themeKey))
              themeMap.put(themeKey, oTheme);
          }else
          {
            if(oTheme.isPhotoCountExist(photoFilter) && !themeMap.get(themeKey) && orientationConstraintSatisfied)
              themeMap.put(themeKey, oTheme);
          }
        }// end of while
 
    return themeMap ;
  } ,
 
  // add some useful get methods
 
  getDefaultSku : function()
  {
    if(this.m_defaultSku == photocard4x8st)
        return photocard4x8;
    if(this.m_defaultSku == photocard5x7st)
            return  photocard5x7;
 
    return this.m_defaultSku;
  },
  getDefaultFilter : function()
  {
    return this.m_defaultPhotoFilter ;
  } ,
  getSkuMap : function()
  {
    return this.m_skuMap ;
  } ,
  getSkus : function()
  {
    return this.m_skus ;
  } ,
  getPhotoFilters : function()
  {
    return this.m_photoFilters ;
  },
  getDefaultCategory : function(){
    return this.m_defaultCategory;
  },
  getDefalutlCategoryDisplayName : function(){
	return this.m_defaultCategoryDisplayName;
  },	
  getOrientationBySkuMap : function(){
    return this.m_orientationBySkuMap;
  },
  getDefaultOrientation : function(sku){
    var orientation  = this.m_orientationBySkuMap.get(sku) ;
    // contains only for photocard4x8 not for photocard4x8st, so this is a hack for stationary sku
        if(orientation  == null && (sku == photocard4x8st || sku == photocard5x7st)){
            orientation = this.m_orientationBySkuMap.get(sku.substring(0,sku.length-2)) ;
        }
    return orientation;
  },
  getFeaturedThemes : function(){
    var themesDataObject =  this.filterCategory("featured", cardsGlobal.selectedSku, cardsGlobal.selectedPhotoCount, cardsGlobal.selectedParentCategory) ;
    if(themesDataObject && themesDataObject.size() == 0){
        this.m_defaultCategory = this.getSkuMap().get(cardsGlobal.selectedSku).getCategories().keys().nextElement();
		themesDataObject =  this.filterCategory(this.m_defaultCategory, cardsGlobal.selectedSku, cardsGlobal.selectedPhotoCount, cardsGlobal.selectedParentCategory) ;
    }
    return themesDataObject;
 },
 getMoreLimit : function(){
    return this.m_moreLimit;
 },
 getCategory: function(categoryName,sku){
    if(typeof sku == 'undefined' || !sku)
    sku=cardsGlobal.selectedSku;
    console.debug('sku='+sku);
    var categories = this.getSkuMap().get(cardsGlobal.selectedSku).getCategories();
    return categories.get(categoryName) ;
 }
 
});// endof class
 
//--------------------------------------------------------------------------------------CCategories
 
var CCategories = Class.create({
 
    initialize : function(categoriesJson, skuObj, isAll){
      this.m_defaultOrientation = undefined;
      this.m_sku = undefined;
      this.m_categories =  Hashtable.getInstance(); // first level excluding sub categories
      this.m_allCategories =  Hashtable.getInstance(); // all, including sug categories
      this.m_skudisplayName = undefined;
      this.m_stskudisplayName = undefined;
 
      this.fillValue(categoriesJson, skuObj, isAll);
  },
 
  fillValue : function(categoriesJson, skuObj, isAll)
  {
    this.m_defaultOrientation = skuObj.defaultorientation ;
    this.m_skudisplayName = skuObj.skudisplayname ;
    this.m_stskudisplayName = skuObj.stskudisplayname ;
    this.m_sku = skuObj.sku ;
    var categories = categoriesJson.categories ;
 
    for(var i=0;i<categories.length;i++)
    {
      var category = categories[i];
      var oCategory = new CCategory(category, skuObj, isAll) ;
//      if(oCategory.hasSubCategories() == true)
//      {
//            var _subCategories = oCategory.getSubCategories() ;
//            var _keys = _subCategories.keys();
//            while(_keys.hasMoreElements())
//            {
//                var _key = _keys.nextElement() ;
//                this.m_categories.put(_key, _subCategories.get(_key));
//            }
//      }
      this.m_categories.put(oCategory.getName() , oCategory);
 
//      var oCategoryForAll = new CCategory(category, null) ;
//      if(oCategory.hasSubCategories() == true)
//      {
//            var _subCategories = oCategory.getSubCategories() ;
//            var _keys = _subCategories.keys();
//            while(_keys.hasMoreElements())
//            {
//                var _key = _keys.nextElement() ;
//                this.m_allCategories.put(_key,_subCategories.get(_key));
//            }
//      }
 
//      this.m_allCategories.put(oCategory.getName(), oCategoryForAll);
    }// end of for
  } ,
 
  getSku : function()
  {
    return this.m_sku ;
  } ,
  getSkuDisplayName : function()
  {
     return this.m_skudisplayName ;
  } ,
  getStSkuDisplayName : function()
  {
     return this.m_stskudisplayName ;
  } ,
  getCategories : function()
  {
    return this.m_categories ;
  } ,
  getAllCategories : function()
  {
    return this.m_allCategories ;
  } ,
  getDefaultOrientation : function()
  {
    return this.m_defaultOrientation ;
  }
} );
 
 
//--------------------------------------------------------------------------------------CCategory
 
// category should represent CategoryInfo object,
// all it need to know is a list of themes and list of subcategories.
// each theme is supposed to what sku it belongs to
/*
    Sample JSON :
 
      {
        "hassubcategories": true,
        "subcategories": [
          {
            "themes": [
              look at theme structure down
            ],
            "hassubcategories": false,
            "name": "christmas_traditional",
            "displayname": "christmas-traditional"
          },
          {
            "themes": [
              look at theme structure down
            ],
            "hassubcategories": false,
            "name": "hanukkah",
            "displayname": "hanukkah"
          }
        ],
        "name": "holiday",
        "displayname": "holiday"
      }
 
  */
var CCategory = Class.create({
 
    initialize : function(categoryJson, skuObj, isAll){
      this.m_name = undefined;
      this.m_displayname = undefined;
      this.m_hasSubCategories = false; // false
      this.m_themes = Hashtable.getInstance();
      this.m_subCategories = undefined;
      this.m_parentCategory = undefined;
 
      this.fillValue(categoryJson, skuObj, isAll);
  },
  fillValue : function(categoryJson, skuObj, isAll)
  {
 
    this.m_hasSubCategories = categoryJson.hassubcategories ;
    this.m_name = categoryJson.name ;
    this.m_displayname = categoryJson.displayname ? categoryJson.displayname : categoryJson.name;
    var _themes = categoryJson.themes ;
    if(_themes)
    {
      for(var i=0;i<_themes.length;i++)
      {
        var themeInfo = _themes[i];
        var oThemeInfo = new CTheme(themeInfo);
        if(isAll)
        {
            if(!this.m_themes.get(oThemeInfo.getName()))
            {
        this.m_themes.put(oThemeInfo.getName(), oThemeInfo );
      }
        }
        else
        {
            if(oThemeInfo.getDefaultSku() == skuObj.sku)
            {
                this.m_themes.put(oThemeInfo.getName(), oThemeInfo );
            }
        }
      }
    } // end of if
 
    if(categoryJson.hassubcategories &&
        categoryJson.hassubcategories == true)
    {
      this.m_subCategories = Hashtable.getInstance();
      var _subCategories = categoryJson.subcategories ;
      for(var q=0;q<_subCategories.length;q++)
      {
        var subcategory = _subCategories[q];
        var oSubCategory = new CCategory(subcategory, skuObj, isAll);
        oSubCategory.m_parentCategory = this.m_name;
        this.m_subCategories.put(oSubCategory.getName() , oSubCategory );
                // to get the all subcategories themes for the main category
//        var themes = oSubCategory.getThemes();
//        var themeKeys = themes.keys();
//        while(themeKeys.hasMoreElements())
//        {
//          var oThemeInfo = themes.get(themeKeys.nextElement());
//          if(isAll)
//          {
//              if(!this.m_themes.get(oThemeInfo.getName()))
//              {
//                  this.m_themes.put(oThemeInfo.getName(), oThemeInfo);
//              }
//          }
//          else
//          {
//              if(oThemeInfo.getDefaultSku() == skuObj.sku)
//              {
//                  this.m_themes.put(oThemeInfo.getName(), oThemeInfo );
//              }
//          }
//        }
        }
      }
  } ,
 
  getName : function()
  {
    return this.m_name ;
  } ,
 
  getDisplayName : function()
  {
    return this.m_displayname;
  } ,
  getThemes : function()
  {
    return this.m_themes;
  } ,
  getSubCategories : function()
  {
    return this.m_subCategories ;
  } ,
  hasSubCategories : function()
  {
    return this.m_hasSubCategories;
  },
  getParentCategory : function()
  {
    return this.m_parentCategory;
  }
}); // end of class
 
//--------------------------------------------------------------------------------------CTheme
var Orientations = new Array();
Orientations[0] = "portrait";
Orientations[1] = "landscape";
Orientations[2] = "square";
 
var CTheme = Class.create({
 
    initialize : function(themeJson){
    this.m_skus = Vector.getInstance();
      this.m_defaultsku = undefined ;
      this.m_name = undefined ;
      this.m_priceText = undefined ;
      this.m_stPriceText = undefined ;
      this.m_displayname = undefined ;
      this.m_formattedphotocount = undefined ;
      this.m_iconUrlsBySku = Hashtable.getInstance();
      this.m_displayText = undefined ; // 4x8 photo card / 5x7 photo card / 4x8 and 5x7 photo card
      this.m_defaultOrientationsBySku = Hashtable.getInstance();
      this.m_minPhotoCount = undefined ;
      this.m_maxPhotoCount = undefined ;
      this.m_availablePhotoCounts = undefined ;
    this.fillValue(themeJson);
    },
 
  fillValue : function(themeJson)
  {
 
    var skus = themeJson.skus ;
 
    this.m_name = themeJson.name ;
    //var orientationsBySku = themeJson.orientationbysku ;
    for(var i=0;i<skus.length;i++)
    {
      var sku = skus[i] ;
      this.m_skus.add(sku);
      var renderer = cardsGlobal.jsonDataObj.renderer;
      //this.m_defaultOrientationsBySku.put(sku,themeJson.orientationbysku[sku]);
      if(this.m_iconUrlsBySku.get(sku))
      {
        for(var j=0;j<Orientations.length;j++)
        {
          /*var urlIConTheme = cardsGlobal.jsonDataObj.themeIcons[this.m_name];
          if(urlIConTheme && urlIConTheme[sku] && (urlIConTheme[sku])[Orientations[j]])
          {
                  var urlIcnosArry = (urlIConTheme[sku])[Orientations[j]];
                  var _urlIconsHash = Hashtable.getInstance();
                  for(var ii=0; ii<urlIcnosArry.length; ii++)
                  {
                          var iconObj = urlIcnosArry[ii];
                          _urlIconsHash.put(iconObj.pCnt, renderer + "/" + iconObj.url);
                  }
                  this.m_iconUrlsBySku.get(sku).put(Orientations[j], _urlIconsHash);
          }*/
          if((themeJson.iconurls[sku]) && (themeJson.iconurls[sku])[Orientations[j]])
          {
            //this.m_iconUrlsBySku.get(sku).put(Orientations[j], (themeJson.iconurls[sku])[Orientations[j]] );
            var urlIcnosArry = (themeJson.iconurls[sku])[Orientations[j]];
                var _urlIconsHash = Hashtable.getInstance();
                for(var ii=0; ii<urlIcnosArry.length; ii++)
                  {
                          var iconObj = urlIcnosArry[ii];
                          _urlIconsHash.put(iconObj.pCnt, renderer + "/" + iconObj.url);
                  }
                this.m_iconUrlsBySku.get(sku).put(Orientations[j], _urlIconsHash);
 
            // this is required for the first/featured category themes only to get the featured icon urs
            if((themeJson.iconurls[sku])["featured_design_"+Orientations[j]])
              {
                this.m_iconUrlsBySku.get(sku).put("featured_design_"+Orientations[j],
                                renderer + "/" + (themeJson.iconurls[sku])["featured_design_"+Orientations[j]] );
              }
          }else if((themeJson.iconurls[sku])["featured_design_"+Orientations[j]]){
            this.m_iconUrlsBySku.get(sku).put("featured_design_"+Orientations[j],
                                renderer + "/" +(themeJson.iconurls[sku])["featured_design_"+Orientations[j]] );
          }
        }
 
      }else
      {
        var _hash = Hashtable.getInstance();
        for(var j=0;j<Orientations.length;j++)
        {
            /*var urlIConTheme = cardsGlobal.jsonDataObj.themeIcons[this.m_name];
            if(urlIConTheme && urlIConTheme[sku] && (urlIConTheme[sku])[Orientations[j]])
            {
                  var urlIcnosArry = (urlIConTheme[sku])[Orientations[j]];
                  var _urlIconsHash = Hashtable.getInstance();
                  for(var ii=0; ii<urlIcnosArry.length; ii++)
                  {
                          var iconObj = urlIcnosArry[ii];
                          _urlIconsHash.put(iconObj.pCnt, renderer + "/" + iconObj.url);
                  }
                  _hash.put(Orientations[j], _urlIconsHash);
            }*/
                if((themeJson.iconurls[sku]) && (themeJson.iconurls[sku])[Orientations[j]])
                {
              // _hash.put(Orientations[j], (themeJson.iconurls[sku])[Orientations[j]] );
              var urlIcnosArry = (themeJson.iconurls[sku])[Orientations[j]];
                  var _urlIconsHash = Hashtable.getInstance();
                  for(var ii=0; ii<urlIcnosArry.length; ii++)
                  {
                          var iconObj = urlIcnosArry[ii];
                          _urlIconsHash.put(iconObj.pCnt, renderer + "/" + iconObj.url);
                  }
 
              _hash.put(Orientations[j], _urlIconsHash);
            if((themeJson.iconurls[sku])["featured_design_"+Orientations[j]])
              {
                _hash.put("featured_design_"+Orientations[j],
                                renderer + "/" +(themeJson.iconurls[sku])["featured_design_"+Orientations[j]] );
              }
          }else if((themeJson.iconurls[sku])["featured_design_"+Orientations[j]]){
            _hash.put("featured_design_"+Orientations[j],
                                renderer + "/" + (themeJson.iconurls[sku])["featured_design_"+Orientations[j]] );
          }
        }
        this.m_iconUrlsBySku.put(sku , _hash)
      }
    }// end of for(i=0;i<skus.length;i++)
 
 
    this.m_priceText = themeJson.pricetext ;
    this.m_stPriceText = themeJson.stPricetext ;
    this.m_displayname = themeJson.displayname ? themeJson.displayname : themeJson.name;
    this.m_defaultsku = themeJson.defaultsku ;
 
    this.m_formattedphotocount = themeJson.formattedphotocount;
    this.m_displayText = themeJson.displaytext; // Eg ; 4x8 photo card / 5x7 photo card / 4x8 and 5x7 photo card
    this.m_minPhotoCount = themeJson.minphotocount;
    this.m_maxPhotoCount = themeJson.maxphotocount;
    this.m_availablePhotoCounts = themeJson.availablephotocounts;
  } ,
 
  // add some useful get methods here
 
  getSkus : function()
  {
    return this.m_skus ;
  } ,
  getPriceText : function()
  {
    return this.m_priceText ;
  },
  getStPriceText : function()
  {
    return this.m_stPriceText ;
  },
  getDefaultSku : function()
  {
    if(this.m_defaultsku == photocard4x8st)
        return photocard4x8;
        if(this.m_defaultsku == photocard5x7st)
        return  photocard5x7;
 
    return this.m_defaultsku ;
  },
  getName : function()
  {
    return this.m_name ;
  },
  getDisplayName : function()
  {
    return this.m_displayname ;
  },
  getFormattedCount : function()
  {
    return this.m_formattedphotocount ;
  },
  getIconUrl : function(sku)
  {
    return this.m_iconUrlsBySku.get(sku);
  },
  getThemeIconUrl : function(sku, orientation, photoCnt, ifFailedDefault)
  {
          console.debug("sku= "+sku+ ": orientation="+orientation+ ": photoCnt="+photoCnt+ ": ifFailedDefault="+ifFailedDefault);
          var iconURL = null, minPhotoCnt = null, minPhotoCntUrl = null;
          // get orientation map
          var oMap = this.m_iconUrlsBySku.get(sku);
          if(oMap)
          {
                  // get photoCount  map
                  var pMap = oMap.get(orientation);
                  if(pMap)
                  {
                          // get url
                          iconURL = pMap.get(photoCnt);
 
                          if(iconURL == null || typeof iconURL == 'function')
                          {
                                  //this is for default
                                  minPhotoCnt = this.getMinValue(pMap.keys().m_array);
                                  if(minPhotoCnt != null)
                                  {
                                          minPhotoCntUrl = pMap.get(minPhotoCnt);
                                  }else
                                  {
                                          minPhotoCnt = 999; //taking max value
                                  }
                          }
                  }
                  // if url not found search in other orientation. Whereas Intl sites are constrained by given orientation
                  if((typeof iconURL == 'undefined' || iconURL == null || typeof iconURL == 'function') &&
                        (_websiteInfo.getRegion() != 'snapfish_eu' || _websiteInfo.getWebsiteName() == 'snapfish_uk'))
                  {
                          // change orientation
                          orientation = (orientation ==  'landscape' ? 'portrait' : 'landscape');
                          pMap = oMap.get(orientation);
                          if(pMap)
                          {
                                  // get url
                                  iconURL = pMap.get(photoCnt);
 
                                  if(iconURL == null || typeof iconURL == 'function')
                                  {
                                          // this is for default
                                          var minPCnt = this.getMinValue(pMap.keys().m_array);
                                          if(minPCnt != null && minPCnt < minPhotoCnt)
                                                  minPhotoCntUrl = pMap.get(minPCnt);
                                  }
                          }
                  }
          }
          //console.debug("iconURL:"+iconURL);
          //if found return the url
          if(typeof iconURL != 'undefined' && iconURL != null && typeof iconURL != 'function')
                  return iconURL;
 
          //if not found take some default url if this flag is true
          if(ifFailedDefault)
          {
                  return minPhotoCntUrl;
          }else
          {
                  //not found
                  return null;
          }
  },
  getMinValue : function(arry)
  {
          if(arry != null && arry.length > 0)
          {
                  var min = arry[0];
                  var len = arry.length;
                  for (var i = 1; i < len; i++)
                  {
                          if (arry[i] < min)
                                  min = arry[i];
                  }
                  return min;
          }else
          {
                  return null;
          }
  },
  getDisplayText : function()
  {
    var txt = this.m_displayText;
    if(txt && sizesTextObj[txt]){
        txt = sizesTextObj[txt];
        txt = txt.split('"').join(''); // to remove double quotes i.e. inche symboles
     }
        return txt;
  },
  getDefaultOrientation : function(sku)
  {
    var orientation  = this.m_defaultOrientationsBySku.get(sku) ;
    // contains only for photocard4x8 not for photocard4x8st, so this is a hack for stationary sku
        if(orientation  == null && (sku == photocard4x8st || sku == photocard5x7st)){
            orientation = this.m_defaultOrientationsBySku.get(sku.substring(0,sku.length-2)) ;
        }
    return orientation;
  } ,
  getMinCount : function()
  {
    return this.m_minPhotoCount ;
  },
  getMaxCount : function()
  {
    return this.m_maxPhotoCount ;
  },
  isPhotoCountExist : function(photoCount)
  {
    for(i=0; i<this.m_availablePhotoCounts.length; i++)
    {
        if(photoCount == this.m_availablePhotoCounts[i])
            return true;
  }
    return false;
  }
});// end of function
 
 
 
//--------------------------------------------------------------------------------------CCardsDesignsDataComponent
 
var CCardsDesignsDataComponent = Class.create({
  //m_url : undefined ,
  initialize: function(url, topicName) {
    this.m_url = url;
    this.topicName = topicName ;
  },
  subscribe :function(_topicName)
  {
    CEventDispatcher.subscribe(_topicName, this , this.load );
  } ,
  load :  function()
  {
    // load this URL, get the data, then publish this message
    if(typeof(loadDataFromDataHost) != "function") throw "util method  loadDataFromDataHost is not defined!" ;
    //util method, look in clientV2.js
 
    var jsonData = loadDataFromDataHost(null, this);
 
  } ,
    setUrl : function (url)
  {
    this.m_url = url;
  } ,
  getReadUrl : function ()
  {
    return this.m_url ;
  } ,
  callbackDataHandler : function (dataObject)
  {
    if(typeof(CEventDispatcher) != "object") throw  "please include clientv2.js!" ;
 
    // you may want to hide the progress bar(s) now.
    // publish to only one topic, let all the view components listen to this
 
    //alert("ok! data is ready now!"+dataObject);
    if(dataObject.status == "not_ok"){
            //alert("Error occured while loading the cards design information :\n\n"+dataObject.message);
        window.status = errorLoadingText;
        $("CardsDesignsProgressDiv").innerHTML = "<span style='position:relative;top:200px;left30px;font-wait:bold;'>"+errorLoadingText+"<br/><font color='white'>"+dataObject.message+"</font></span>";
        cardsGlobal.cardDesignsObj = undefined;
        return;
    }
    cardsGlobal.jsonDataObj = dataObject;
    cardsGlobal.cardDesignsObj = new CCardsDesigns(dataObject);
    // now publish the call back to occasion tree view component
        console.debug("CCardsDesignsDataComponent : publish ");
    CEventDispatcher.publish(this.topicName , cardsGlobal.cardDesignsObj );
 
  }
});// end of function
 
//--------------------------------------------------------------------------------------CCardsThemeLayoutDataComponent
 
var CCardsThemeLayoutDataComponent = Class.create({
 
  initialize: function(topicName) {
    this.m_url = "";
    this.topicName = topicName ;
    this.dataObject = undefined;
    this.themeDisplayName = undefined;
    console.debug("CCardsThemeLayoutDataComponent : initialize :topicName : "+topicName);
  },
  setUrl : function(url){
    this.m_url = url;
  },
  subscribe :function(_topicName)
  {
    CEventDispatcher.subscribe(_topicName, this , this.load );
    console.debug("CCardsThemeLayoutDataComponent : subscribing to : "+_topicName);
  } ,
  load :  function(message)
  {
    console.debug("CCardsThemeLayoutDataComponent : load : message : "+message);
    this.m_url = message.url;
    if(typeof(loadDataFromDataHost) != "function") throw "util method  loadDataFromDataHost is not defined!" ;
    loadDataFromDataHost(null, this);
  } ,
 
  getReadUrl : function ()
  {
    return this.m_url ;
  } ,
  callbackDataHandler : function (dataObject)
  {
    console.debug("CCardsThemeLayoutDataComponent : in callbackDataHandler with json data : "+dataObject);
    if(typeof(CEventDispatcher) != "object") throw  "please include clientv2.js!" ;
    console.debug("CCardsThemeLayoutDataComponent : in callbackDataHandler publising for topic  : "+this.topicName);
    if(dataObject.status == "not_ok"){
                alert("Error occured while loading the theme layouts information");
        window.status = "Error occured while loading the theme layouts information";
            this.dataObject = Hashtable.getInstance();
            return;
    }
    cardsGlobal.cardLayoutsObj = this.filterBySku(dataObject);
    CEventDispatcher.publish(this.topicName , [cardsGlobal.cardLayoutsObj,this.themeDisplayName]);
  },
  filterBySku : function(dataObject){
    var skus = dataObject.skus;
    var skuLayoutsMap = Hashtable.getInstance();
    for(var i = 0; i < skus.length; i++){
 
            var templates = new Array();
        if(!(dataObject[skus[i]] && dataObject[skus[i]].themetemplates)) continue;
        this.themeDisplayName = dataObject[skus[i]].displayname;
        // this is all to get the templates from front[[t11,t12...],[t22,t23...],...]
        var frontArrays = dataObject[skus[i]].themetemplates.front;
        for(var j = 0 ; j < frontArrays.length; j++){
            var frontArray = frontArrays[j];
            for(var k = 0 ; k < frontArray.length ; k++){
                templates.push(frontArray[k]);
            }
        }
        if(templates.length > 0)
            skuLayoutsMap.put(skus[i],templates);
 
    }
    return skuLayoutsMap;
  },
  getLayoutObject : function(skuName, layoutId, orientation){
    var layoutsBySku = cardsGlobal.cardLayoutsObj.get(skuName);
    if(layoutsBySku){
        for(var i = 0 ; i < layoutsBySku.length; i++){
            var layoutObj = layoutsBySku[i];
            if(layoutObj.templatename == layoutId && layoutObj.orientation == (orientation+".xml")){
                return layoutObj;
            }
        }
    }
  }
});// end of function
 
 
//--------------------------------------------------------------------------------------COccasionsTreeViewComponent
 
var COccasionsTreeViewComponent = Class.create({
 
  initialize: function(div,category, parentCategory) {
    this.m_div = $(div);
    this.moreDiv = $("More"+div);
    this.linkStyle = "black-link";
    this.prevLinkStyle = "black-link";
    cardsGlobal.selectedCategory = category != "null"? category :undefined;
    cardsGlobal.selectedParentCategory = parentCategory != "null"? parentCategory :undefined;
    this.linkInMorePopup = "false";
  },
  subscribe : function(topicName)
  {
    //this.m_defaultCategory = defaultCategory ;
    CEventDispatcher.subscribe( topicName , this , this.renderCategoriesTree );
 
  } , // end of init
  renderCategoriesTree : function( message )
  {
    // recollecting references
      this.m_div = $(this.m_div.id);
      this.moreDiv = $(this.moreDiv.id);
      this.linkStyle = "black-link";
    this.prevLinkStyle = "black-link";
        //removing existing nodes
    var _children = $(this.m_div).childNodes ;
    for(var i=0;i<_children.length;i++)
    {
      $(this.m_div).removeChild($(this.m_div).childNodes[i]);
        }
        _children = $(this.moreDiv).childNodes ;
    for(var i=0;i<_children.length;i++)
    {
      $(this.moreDiv).removeChild($(this.moreDiv).childNodes[i]);
        }
 
        var dataObject = cardsGlobal.cardDesignsObj;
        var sku = cardsGlobal.selectedSku;
 
        // this is all to collect the skus categories if selected all
    var selectedSkus;
    if(sku == "all"){
        selectedSkus = dataObject.getSkus();
    }else{
        selectedSkus = Vector.getInstance();
        selectedSkus.add(sku);
    }
    var categories = Hashtable.getInstance();
    for(var i = 0 ; i < selectedSkus.size(); i++){
 
        var cat = dataObject.getSkuMap().get(selectedSkus.get(i)).getCategories();
        var keys = cat.keys();
        while(keys.hasMoreElements()){
          var key = keys.nextElement();
          if(categories.contains(key)) continue; // to preserve the category order, otherwise if same key found then .put() pushes that to the end, so losses order
          categories.put(key,cat.get(key));
        }
    }
    sku = selectedSkus.get(0);
    // To make featured as the Default Category if available
    if(!(_websiteInfo.getWebsiteName() == "walmart_us" || _websiteInfo.getWebsiteName() == "walgreens_us")){
    if(cardsGlobal.selectedCategory == undefined)
        cardsGlobal.selectedCategory = "featured";
    }
    // if the selectected category(featured) is available in this category list then set it or use first category for selection
    if(categories.contains(cardsGlobal.selectedCategory)){
        cardsGlobal.selectedCategory = cardsGlobal.selectedCategory ? cardsGlobal.selectedCategory  : categories.keys().nextElement();
        cardsGlobal.selectedParentCategory = undefined;
    }else{
         //This is for subcategory selection from url
        var isSubCatFound = false;
        var keys = categories.keys();
        while(keys.hasMoreElements()){
          var key = keys.nextElement();
          var parentCat = categories.get(key);
          if(parentCat.hasSubCategories())
          {
            var subCat = parentCat.getSubCategories();
            if(subCat.contains(cardsGlobal.selectedCategory))
            {
                cardsGlobal.selectedParentCategory = key;
                isSubCatFound = true;
                break;
            }
          }
        }
 
        //if not take first category/first sub category to dispaly
        if(!isSubCatFound)
        {
            var cat = categories.keys().nextElement();
            try{
              var parentCat = categories.get(cat);
              var sub = parentCat.hasSubCategories();
              if(sub){
                var subCat = parentCat.getSubCategories();
                cardsGlobal.selectedCategory = subCat.keys().nextElement();
                cardsGlobal.selectedParentCategory = cat;
              }else{
                cardsGlobal.selectedCategory = cat;
                cardsGlobal.selectedParentCategory = undefined;
              }
            }catch(e){
              cardsGlobal.selectedCategory = cat;
            }
        }
    }
 
    // builing selected category theme pages, a call to themepagination object
    if(cardsGlobal.selectedParentCategory != undefined)
        CEventDispatcher.publish( "categoryview" ,  {"selectedCategory" : cardsGlobal.selectedCategory, "categoryParent" : cardsGlobal.selectedParentCategory} );
    else
        CEventDispatcher.publish( "categoryview" ,  {"selectedCategory" : cardsGlobal.selectedCategory} );
 
    var categoryKeys = categories.keys() ;
 
    var _ul = document.createElement("ul");
    var mainDiv = $(this.m_div);
 
    var catLimitCount =  dataObject.getMoreLimit();
    var categoryCount = 0;
    this.linkInMorePopup = "false";
    while(categoryKeys.hasMoreElements())
    {
      var categoryKey = categoryKeys.nextElement() ;
      var categoryObject = categories.get( categoryKey ) ;
 
 
            if(categoryCount == catLimitCount && this.linkInMorePopup != "true" && !(_websiteInfo.getWebsiteName() == "snapfish_uk" && window.notebook9x6 == sku) && !(_websiteInfo.getWebsiteName() == "walgreens_us")){
                    // creating more link list item
                    var li = document.createElement("li");
                    var moreLink = new Element("a",{"href":"javascript:showMoreLayer()","class":"black-link","title":seeMoreOccasionsText});
                    moreLink.appendChild(document.createTextNode(moreText));
                    li.appendChild(moreLink)
                    _ul.appendChild(li);
                    // adding already created list to main div
                    $(this.m_div).appendChild(_ul);
                    // replacing the main div to add the upcomming categories to more div
                    mainDiv = this.moreDiv;
                    _ul = document.createElement("ul");
                    this.linkStyle = "more-occasions-link";
                    this.linkInMorePopup = "true";
            }
 
      if(categoryObject.hasSubCategories())
      {
        var categoryLi = new Element("li",{"class":this.linkStyle,"isinmorepopup":this.linkInMorePopup});
 
        if(categoryObject.getDisplayName())
          categoryLi.appendChild(document.createTextNode(categoryObject.getDisplayName()));
        else
          categoryLi.appendChild(document.createTextNode(categoryObject.getName()));
 
          _ul.appendChild(categoryLi);
        // to show subcategories in the main box when they exceeds the limit
        var subCatSize = categoryObject.getSubCategories().size();
        categoryCount =  categoryCount + subCatSize;
        if( catLimitCount < categoryCount && this.linkInMorePopup != "true"){
            catLimitCount = categoryCount;
        }
 
        _ul.appendChild(this.renderSubCategories(categoryObject, document.createElement("ul")));
 
      }else{
        _ul.appendChild(this.renderCategoryAnchor(categoryObject));
        if(categoryObject.getName() == "featured"){
                cardsGlobal.hasFeatured = true;
        }
       categoryCount++;
      }
    }
    mainDiv.appendChild(_ul);
    // selecting default/selected occasion.
    //if(cardsGlobal.selectedCategory){ // if not required
        this.setSelection({selectedCategory:cardsGlobal.selectedCategory,categoryParent:cardsGlobal.selectedParentCategory});
        if(designsTabContainer.currentPageObj.name == "SelectDesign"){
            $("CardsDesignsProgressDiv").style.display = "none";
            $("SelectDesign").style.display = "block";
        }
    //}
    return ;
  } ,// end of renderCategoriesTree
  renderSubCategories : function(categoryObject, categoryUl )
  {
 
    var categoryDisplayName = undefined ;
    if(categoryObject.getDisplayName())
      categoryDisplayName =  document.createTextNode(categoryObject.getDisplayName());
    else
      categoryDisplayName = document.createTextNode(categoryObject.getName());
    if(categoryObject.hasSubCategories())
    {
      var subCategories = categoryObject.getSubCategories();
      var subCategoryKeys = subCategories.keys() ;
      while(subCategoryKeys.hasMoreElements())
      {
        var subCategoryKey = subCategoryKeys.nextElement() ;
        var subCategoryObj = subCategories.get(subCategoryKey);
        if(subCategoryObj.hasSubCategories()){
            // if the subcategory has again some subcategories then triggering a recursive call
            categoryUl.appendChild(this.renderSubCategories(subCategoryObj, document.createElement("ul") ) );
        }else{
            categoryUl.appendChild(this.renderCategoryAnchor(subCategoryObj));
        }
      }
    }else
    {
      categoryUl.appendChild(this.renderCategoryAnchor(categoryObject));
    }
 
    return categoryUl ;
 
  },
  renderCategoryAnchor : function(categoryObject)
  {
    var li = document.createElement("li");
    var categoryName = categoryObject.getName();
    var jsParams = "";
    if(categoryObject.getParentCategory() != undefined)
    {
        jsParams = "'"+CURLEncoder.encode(categoryObject.getName())+"','"+categoryObject.getParentCategory()+"'";
    }else
    {
        jsParams = "'"+CURLEncoder.encode(categoryObject.getName())+"'";
    }
    var categoryAnchor = new Element("a",{"id":categoryName+"Link","isinmorepopup":this.linkInMorePopup,
        "href":"javascript:filterByCategory("+jsParams+");","class":this.linkStyle});
    var categoryDisplayName = undefined ;
    if(categoryObject.getDisplayName())
      categoryDisplayName =  document.createTextNode(initCapital(categoryObject.getDisplayName()));
    else
      categoryDisplayName = document.createTextNode(initCapital(categoryObject.getName()));
    categoryAnchor.appendChild(categoryDisplayName);
    li.appendChild(categoryAnchor);
    return li ;
  },
  setSelection: function(categoryObject){
        var prevSelCatLink = $(cardsGlobal.selectedCategory+"Link");
        var currSelCatLink = $(categoryObject.selectedCategory+"Link");
        if(prevSelCatLink){ // restoring previously selected link stile
            prevSelCatLink.removeClassName("orange-boldtext");
            prevSelCatLink.addClassName(this.prevLinkStyle);
        }
        if(currSelCatLink){ // applying to selected link
            this.prevLinkStyle = currSelCatLink.readAttribute("class");
            currSelCatLink.removeClassName(this.prevLinkStyle);
            currSelCatLink.addClassName("orange-boldtext");
        }
        cardsGlobal.selectedCategory = categoryObject.selectedCategory;
        cardsGlobal.selectedParentCategory = categoryObject.categoryParent;
        var isInMorePopup = currSelCatLink.readAttribute("isinmorepopup");
        if(isInMorePopup == "true"){
            //showMoreLayer(); // FIX ME : toggling problem
        }
  }
 
});// end of view component
 
//--------------------------------------------------------------------------------------CSizeViewComponent
var CSizeViewComponent = Class.create({
  //m_div = undefined ;
  initialize :  function(div)
  {
    this.m_div = $(div) ;
  } ,
  subscribe : function(topicName)
  {
    CEventDispatcher.subscribe( topicName , this , this.renderSizes );
 
  } ,
  renderSizes : function(pageDataObject)
  {
    // render the sizes drop down here and add onchange event to it
    this.m_div = $(this.m_div.id);
    var _children = $(this.m_div).childNodes ;
    for(var i=0;i<_children.length;i++)
    {
      $(this.m_div).removeChild($(this.m_div).childNodes[i]);
    }
 
    var skuMap = pageDataObject.getSkuMap();
    var skuKeys = skuMap.keys() ;
 
    /*if(skuMap.size() <= 1){
      var skuDisplayName = skuMap.size() == 0 ? "0" : skuMap.get(skuKeys.nextElement()).getSkuDisplayName();
      $(this.m_div).appendChild(document.createTextNode(skuDisplayName));
    }else{*/
 
    var defaultSku = pageDataObject.getDefaultSku();
    if(skuMap.size() > 1)
    {
        var selectElement = document.createElement('select');
 
        $(selectElement).setStyle({fontSize:'11px'});
        $(selectElement).setStyle({width:'130px'});
        $(selectElement).observe('change', filterBySku);
 
        var option = document.createElement("option");
        var skuDisplayName = document.createTextNode(allSizeText);
        option.setAttribute("value", "all");
        option.appendChild(skuDisplayName);
        selectElement.appendChild(option);
 
        while(skuKeys.hasMoreElements())
        {
          var sku =  skuKeys.nextElement();
          if(sku == "all")
            continue;
              var option = document.createElement("option");
              var displayName = skuMap.get(sku).getSkuDisplayName();
              if(cardsGlobal.isStationery)
                displayName = skuMap.get(sku).getStSkuDisplayName();
              displayName = displayName.split('"').join(''); // to remove double quotes,just for display
              var skuDisplayName = document.createTextNode(displayName);
              option.setAttribute("value", sku);
              option.appendChild(skuDisplayName);
              selectElement.appendChild(option);
         }
 
         $(this.m_div).appendChild(selectElement);
 
         defaultSku = "all";
 
         if(cardsGlobal.selectedSku && defaultSku != cardsGlobal.selectedSku && skuMap.contains(cardsGlobal.selectedSku)){
            defaultSku = cardsGlobal.selectedSku;
        }
        selectElement.value = defaultSku;
 
    }else{
         $(this.m_div).style.display = "none";
         $("SizeTextDiv").style.display = "none";
    }
        cardsGlobal.selectedSku = defaultSku;
    CEventDispatcher.publish( "sizechanged" ,  {"sku":defaultSku } );
  },
  getSelectedSku : function()
  {
    //by assuming only one childern will be there and that child is select element.
    //if any changes are there, then we have to modify this code as per new changes.
    this.m_div = $(this.m_div.id);
    $(this.m_div).childNodes ;
    if($(this.m_div).childNodes)
    {
        return $(this.m_div).childNodes[0].value;
    }
    return null;
  }
});
 
//--------------------------------------------------------------------------------------CPhotoFilterViewComponent
var CPhotoFilterViewComponent = Class.create({
  //this.m_div = undefined ;
  initialize :  function(div)
  {
    this.m_div = $(div) ;
  } ,
  subscribe : function(topicName)
  {
    CEventDispatcher.subscribe( topicName , this , this.renderPhotoFilter );
  } ,
  renderPhotoFilter : function(pageDataObject)
  {
 
      this.m_div = $(this.m_div.id);
        // removing existing child nodes from main div
    var _children = $(this.m_div).childNodes ;
    for(var i=0;i<_children.length;i++)
    {
      $(this.m_div).removeChild($(this.m_div).childNodes[i]);
        }
    var selectElement = document.createElement('select');
    $(selectElement).setStyle({fontSize:'11px'});
    //selectElement.setAttribute("onchange", "javascript:filterByPhotoCount(this.value);");
    $(selectElement).observe('change', filterByPhotoCount);
 
    var filterMap = pageDataObject.getPhotoFilters();
 
    var filterKeys = filterMap.keys() ;
    var option, filter;
    while(filterKeys.hasMoreElements())
    {
      filter =  filterKeys.nextElement();
      option = document.createElement("option");
      var filterDisplayName=filterMap.get(filter);
      if(typeof view_all_text != 'undefined' && filterDisplayName == 'view all')
      filterDisplayName=view_all_text;
      filterDisplayName = document.createTextNode(filterDisplayName);
      option.setAttribute("value", filter);
      option.appendChild(filterDisplayName);
      selectElement.appendChild(option);
    }
    selectElement.value = filter; // to select the last element i.e. "4+"
        cardsGlobal.selectedPhotoCount = filter;
 
    $(this.m_div).appendChild(selectElement);
 
  }
}); // end of class
 
//--------------------------------------------------------------------------------------CCategoryViewComponent
 
var CCategoryViewComponent = Class.create({
  initialize : function(div)
  {
    this.m_div = $(div) ;
  } , // end of init
  subscribe : function(topicName)
  {
    CEventDispatcher.subscribe( topicName , this , this.renderCategory );
  } ,
  renderCategory : function( dataObject )
  {
        this.m_div = $(this.m_div.id);
    while (this.m_div.firstChild) {
        this.m_div.removeChild(this.m_div.firstChild);
        }
 
    if(!dataObject) {
        this.m_div.innerHTML = noThemesText;
        return;
    }
 
    var themesDataObject  =   dataObject.themesDataObject ;
    var selectedCategory  =   dataObject.selectedCategory ;
    var photoFilter       =   dataObject.photoFilter ;
    var sku               =   dataObject.sku ;
 
    var filteredThemes =  themesDataObject; //categoriesObject.filterCategory(selectedCategory, sku, photoFilter) ;
    if(filteredThemes.size() <= 0) {
        this.m_div.innerHTML = noThemesText;
        return;
    }
 
    var themeDom = $(document.createElement("div"));
 
    var themeKeys = filteredThemes.keys() ;
    while(themeKeys.hasMoreElements())
    {
      var themeKey = themeKeys.nextElement();
      var oTheme = filteredThemes.get(themeKey) ;
        var themeSku = (sku == "all") ? oTheme.getDefaultSku() : sku; // this required when user selects "all sizes" option for photocards
        var orientationBySku = cardsGlobal.cardDesignsObj.getDefaultOrientation(themeSku);
        if(_websiteInfo.getRegion() == 'snapfish_eu' && _websiteInfo.getWebsiteName()!= 'snapfish_uk' && typeof cardsGlobal.selectedOrientation != 'undefined')
        orientationBySku=cardsGlobal.selectedOrientation;
 
          if(photoFilter == 'all')
                  photoFilter=1;
 
          console.debug("oTheme : "+oTheme.getName());
 
          var iconUrl = oTheme.getThemeIconUrl(themeSku, orientationBySku, photoFilter, true);
 
      if(typeof iconUrl == 'undefined' || typeof iconUrl == 'function' || iconUrl == null)
      {
          console.debug("oTheme : "+iconUrl);
          console.debug("oTheme : "+oTheme.getName());
          console.debug("ERROR:  There is some problem in getting url icon...! ");
        continue;
      }
      //verifying weather orientation is changed or not
      //if orientation change then take other orientation
      //As MONTAGE_LAYOUT parameter is removed from icon url the below
      // condition causing problem so commenting it.
      /*if(iconUrl.indexOf(orientationBySku+".xml") == -1)
      {
          orientationBySku = (orientationBySku == 'landscape'? 'portrait': 'landscape');
      }*/
 
      // to get the padding top for the icon getting width and height from rendered url
      var paddingTop = orientationBySku == "landscape" ? 70 : 0;
      var iconWidth=0; var iconHeight = 0;
      var local_isStockings = (window.photoStockingsLarge == themeSku || window.photoStockingsSmall == themeSku);
      var wh = new Array();
if(iconUrl != null){
         if(iconUrl.indexOf('renderingicon') == -1){
 
          start = iconUrl.indexOf("/MONTAGE_OUTPUT=");
          end = iconUrl.indexOf("/",start+1);
          wh = iconUrl.substring(start+"/MONTAGE_OUTPUT=".length,end); // ex : 158x102
                  wh = wh.split("x");
          }else{
                        var strArray = iconUrl.split('/');
                        var width_str = null;
                        var height_str = null;
                        for(var i=0; i<strArray.length; i++){
                                if(strArray[i].indexOf('w=') != -1){
                                        width_str = strArray[i];
                                }
                                if(strArray[i].indexOf('h=') != -1){
                                        height_str = strArray[i];
                                }
                                if(width_str & height_str){
                                        break;
                                }
                        }
                        wh[0] = parseInt(width_str.split("=")[1]);
                        wh[1] = parseInt(height_str.split("=")[1]);
          }
          iconWidth = wh[0]; iconHeight = wh[1];
          paddingTop = 158 - (isNaN(wh[1])? 0 : wh[1]);
      }
      var themeName =  oTheme.getDisplayName() ;
      themeName = (!themeName) ? oTheme.getName() : themeName ;
      var cardDiv = "";
      if(window.addresslabel == themeSku)
      {
          if(_websiteInfo.getWebsiteName() != 'walmart_us')
                  cardDiv = new Element("div",{"id":themeKey,"class":"cards","style":"height: 150px;"});
              else
                  cardDiv = new Element("div",{"id":themeKey,"class":"cards","style":"height: 170px;"});
      }
      else {
          cardDiv = new Element("div",{"id":themeKey,"class":"cards"});
      }
      var imageDiv = "";
      if((_websiteInfo.getRegion() == 'snapfish_eu' && _websiteInfo.getWebsiteName() != 'snapfish_uk')){
        imageDiv = new Element("div",{"class":"img","align":"center"});
      }else if(window.addresslabel == themeSku){
        if(_websiteInfo.getWebsiteName() != 'walmart_us')
                imageDiv = new Element("div",{"class":"img","align":"center","style":"position: relative;height: 60px;"});
            else
                imageDiv = new Element("div",{"class":"img","align":"center","style":"position: relative;height: 75px;"});
      }else if(local_isStockings){
            paddingTop = 25;
            imageDiv = new Element("div",{"class":"img","align":"center","style":"position: relative;height:146px;width:146px;"});
      }
      else{
        imageDiv = new Element("div",{"class":"img","align":"center","style":"position: relative;"});
      }
      themeURLIndex = setThemeIDArray(encodeURI(iconUrl));
      var anchorTag = new Element("a",{"href":"JavaScript:hideThemeLayouts();showLayoutsPage('"+themeKey+"','"+orientationBySku+"','"+themeSku+"', undefined,'"+themeURLIndex+"')"});
      if(_websiteInfo.getRegion() == 'snapfish_eu' && _websiteInfo.getWebsiteName()!= 'snapfish_uk'){
        paddingTop = "8px";
        if(orientationBySku.indexOf('landscape')!= -1){
            cardDiv.removeClassName('cards');
            cardDiv.addClassName('cards-lscape');
        }
      }
      var themeImage = null;
      if(iconUrl && iconUrl.length > 2048 && isIE){ // to solve image loading in IE for long urls
            selfLoadUrl = getSelfLoadUrl(iconUrl);
            themeImage = new Element("div",{"title":themeName,"style":"margin-top:"+paddingTop+"px;width:"+iconWidth+"px;height:"+iconHeight+"px;"});
            themeURLIndex = setThemeIDArray(encodeURI(iconUrl));
            var iFrameHtml = "<div style='position:absolute;z-index:100;height:"+iconHeight+"px;width:"+iconWidth+"px'>"+
                "<a href=\"JavaScript:hideThemeLayouts();showLayoutsPage('"+themeKey+"','"+orientationBySku+"','"+themeSku+"', undefined,'"+themeURLIndex+"')\"><img src='"+spacerImg+"' width='"+iconWidth+"' height='"+iconHeight+"' style='cursor:hand'></img></a></div>"+
                "<div style='solid;height:"+iconHeight+"px;width:"+iconWidth+"px'>"+
                "<iframe src='"+selfLoadUrl+"' border='"+0+"' width='"+iconWidth+"' height='"+iconHeight+"' frameborder='no'    border='0'    marginwidth='0'   marginheight='0'   scrolling='no'></iframe></div>";
            themeImage.innerHTML = iFrameHtml ;
      }else if(window.addresslabel == themeSku)
      {
           themeImage = new Element("img",{"src":iconUrl,"title":themeName});
      }
      else{
                  if(_websiteInfo.getWebsiteName()== 'walmart_us'){
                          if(local_isStockings){
                           if(window.photoStockingsSmall == themeSku)
                             themeImage = new Element("img",{"src":iconUrl,"title":themeName,"style":"margin-left:35px;margin-top:"+paddingTop+"px;border:solid 0px #dddddd"});
                           else
                             themeImage = new Element("img",{"src":iconUrl,"title":themeName,"style":"margin-left:30px;margin-top:"+paddingTop+"px;border:solid 0px #dddddd"});
                          }else{
                            themeImage = new Element("img",{"src":iconUrl,"title":themeName,"style":"margin-top:"+paddingTop+"px;border:solid 1px #dddddd"});
                          }
                  }else{
            themeImage = new Element("img",{"src":iconUrl,"title":themeName,"style":"margin-top:"+paddingTop+"px;"});
          }
      }
      if(window.notebook9x6 == themeSku && (themeSku.toLowerCase().indexOf("notebook")>=0) && !('notepads'==themeSku || 'Stickersx48'==themeSku || 'Tag;luggage'==themeSku)){
        if(_websiteInfo.getRegion() == 'snapfish_eu' && _websiteInfo.getWebsiteName() != 'snapfish_uk'){
                var spiralImgDiv = new Element("div",{"style":"position: absolute; top: -5px; left: 23px;"});
        }else{
                var spiralImgDiv = new Element("div",{"style":"position: absolute; top: 9px; left: 23px;"});
        }
        anchorTag.appendChild(spiralImgDiv) ;
        var spiralImg = new Element("img",{"style":"border: 0px;","src":"/default/images/notebooks/select_design_rings.png"});
        spiralImgDiv.appendChild(spiralImg);
      }
      if(window.walmartJournal == themeSku){
        var spiralImgDiv = new Element("div",{"style":"position: absolute; top: 52px; left: 81px;"});
        anchorTag.appendChild(spiralImgDiv) ;
        var spiralImg = new Element("img",{"style":"border: 0px;","src":"/default/images/walmart/walmart_us/journals/select_designs.gif"});
        spiralImgDiv.appendChild(spiralImg);
      }
      if(window.photoStockingsSmall == themeSku){
        var whiteCuffImgDiv = new Element("div",{"style":"position: absolute; top: 1px; left: 43px;"});
        anchorTag.appendChild(whiteCuffImgDiv) ;
        var whiteCuffImg = new Element("img",{"style":"border: 0px;width:63;height:24;","src":"/default/images/walmart/walmart_us/stockings/create_stocking_cuff.jpg"});
        whiteCuffImgDiv.appendChild(whiteCuffImg);
      }else if(window.photoStockingsLarge == themeSku){
        var whiteCuffImgDiv = new Element("div",{"style":"position: absolute; top: 1px; left: 50px;"});
        anchorTag.appendChild(whiteCuffImgDiv) ;
        var whiteCuffImg = new Element("img",{"style":"border: 0px;width:52;height:24;","src":"/default/images/walmart/walmart_us/stockings/create_stocking_cuff.jpg"});
        whiteCuffImgDiv.appendChild(whiteCuffImg);
      }
      anchorTag.appendChild( themeImage ) ;
      imageDiv.appendChild(anchorTag);
 
      // theme name link
      var cardsTextDiv;
      if(_websiteInfo.getWebsiteName() != 'walmart_us')
        cardsTextDiv = new Element("div",{"class":"cards-text"},{"style":"height:57px"});
      else
        cardsTextDiv = new Element("div",{"class":"cards-text"});
      themeURLIndex = setThemeIDArray(encodeURI(iconUrl));
      var anchorTag = new Element("a",{"style":"font-weight:bold","href":"JavaScript:hideThemeLayouts();showLayoutsPage('"+themeKey+"','"+orientationBySku+"','"+themeSku+"', undefined,'"+themeURLIndex+"')"});
 
      if( _websiteInfo.getWebsiteName() == "walgreens_us")
            themeName = themeName.length > 25 ? themeName.substring(0,25)+" ..." : themeName;
      else if((_websiteInfo.getRegion() == 'snapfish_eu' && _websiteInfo.getWebsiteName() != 'snapfish_uk') || _websiteInfo.getWebsiteName() == "walmart_us")
            themeName = themeName //.length > 23 ? themeName.substring(0,23)+"<br/>"+themeName.slice(23) : themeName;
      else
            themeName = themeName.length > 25 ? themeName.substring(0,25)+"<br/>"+themeName.slice(25) : themeName;
          if( _websiteInfo.getWebsiteName() == "walmart_us" && window.addresslabel == themeSku)
                  anchorTag.innerHTML = initCaps(themeName);
          else
                  anchorTag.innerHTML = themeName;
      cardsTextDiv.appendChild(anchorTag);
 
      // text section below theme name link
      var moreLayoutsDiv = new Element("div",{"class":"more-layouts"});
      // size text
      var displayText = (window.notebook9x6 == themeSku && _websiteInfo.getWebsiteName() == 'snapfish_uk') ? notebooksDisplayText : oTheme.getDisplayText();
      if(_websiteInfo.getRegion() != 'snapfish_eu' || _websiteInfo.getWebsiteName() == 'snapfish_uk'){
         if(displayText.text != "/"/"" ){
                  var moreLayoutsDisplayTextNode = document.createTextNode(displayText);
                  moreLayoutsDiv.appendChild(moreLayoutsDisplayTextNode);
              moreLayoutsDiv.appendChild(document.createElement("br"));
          }
      }
      if(window.notebook9x6 != themeSku && window.addresslabel != themeSku && themeSku!=window.plushBabyBlanket){
      // + image link
      anchorTag = new Element("a",{"href":"JavaScript:showThemeLayouts('"+themeKey+"','"+orientationBySku+"')"});
      var plusTab = new Element("img",{"src":plusTabSrc,"hspace":"4","style":"pointer:hand;","title":plusTabAltText});
      
      anchorTag.appendChild(plusTab)
      moreLayoutsDiv.appendChild(anchorTag);
       }
      // photo count text
      var photoCount = 1;    
      if(typeof isPhotoCountDisplaySupported != "undefined" && isPhotoCountDisplaySupported == "false"){    	  
    	  photoCount = "";
      }else{
         if(oTheme.getMinCount() == oTheme.getMaxCount()){
             photoCount = oTheme.getMinCount();
             photoCount = parseInt(photoCount) == 1 ? photoCount+" "+photoText : photoCount+" "+photosText;
         }else{
             photoCount = oTheme.getMinCount()+"-"+oTheme.getMaxCount()+" "+photosText;
         }
      }
 
      var moreLayoutsTextNode = document.createTextNode(photoCount);
      if(window.addresslabel != themeSku && themeSku!=window.plushBabyBlanket)
              moreLayoutsDiv.appendChild(moreLayoutsTextNode);
      // price text
      var priceContentDiv = new Element("div",{"class":"blue-content","style":"font-weight:bold"});
 
      if(cardsGlobal.isStationery)
        priceContentDiv.innerHTML = oTheme.getStPriceText();
      else
        priceContentDiv.innerHTML = oTheme.getPriceText();
 
      if( _websiteInfo.getWebsiteName() == "walgreens_us" || _websiteInfo.getWebsiteName() == "walmart_us"){
      if(cardsGlobal.isStationery)
        priceContentDiv.innerHTML = asLowAsText+" "+oTheme.getStPriceText()+tailText;
      else{
        if(window.addresslabel == themeSku)
                priceContentDiv.innerHTML = asLowAsText+" "+"<span><font color='#D00000'>"+oTheme.getPriceText()+"</font></span>"+tailText;
            else
                priceContentDiv.innerHTML = asLowAsText+" "+oTheme.getPriceText()+tailText;
      }
      }
 
      if(_websiteInfo.getRegion() != 'snapfish_eu' || _websiteInfo.getWebsiteName()== 'snapfish_uk')
      moreLayoutsDiv.appendChild(priceContentDiv);
 
      cardsTextDiv.appendChild(moreLayoutsDiv);
 
      cardDiv.appendChild(imageDiv);
      cardDiv.appendChild(cardsTextDiv);
 
      themeDom.appendChild(cardDiv);
 
    }// ened of while
    themeDom.addClassName("content-left");
    this.m_div.appendChild(themeDom);
    if(dojo.byId('catName')){
        var catDisplayName=cardsGlobal.cardDesignsObj.getCategory(selectedCategory,sku).getDisplayName();
        if(catDisplayName)
        dojo.byId('catName').innerHTML=catDisplayName;
        else dojo.byId('catName').innerHTML=selectedCategory;
    }
 
    return ;
  }  // end of renderCategoriesTree
});// end of class
 
//--------------------------------------------------------------------------------------CThemePaginationComponent
 
var CThemePaginationComponent = Class.create({
 
    initialize : function(main_div,themeCountRangeDiv,themeCountTotolDiv,themeCountPageListDiv,viewAllLinkText,defaultCount){
        this.m_div = $(main_div);
        this.m_themeCountRangeDiv = $(themeCountRangeDiv);
        this.m_themeCountTotolDiv = $(themeCountTotolDiv);
        this.m_themeCountPageListDiv = $(themeCountPageListDiv);
        this.m_themeCountPageListDiv2 = $(themeCountPageListDiv+"2");
        this.m_viewAllLinkText = viewAllLinkText;
        this.m_defaultCount = defaultCount && !isNaN(defaultCount) ? defaultCount : 12;
        this.m_totalThemeCount = 0;
        this.m_totalPages = 1;
        this.m_filteredThemes=undefined;
        this.m_currentPageNumber=1;
    } , // end of init
    subscribe : function(topicName)
    {
      CEventDispatcher.subscribe( topicName , this , this.renderPage );
    } ,
    renderPage : function( message )
    {
 
        this.m_currentPageNumber=1; // since only one instance is serviing for all calls, reinitializing it
        if(_websiteInfo.getRegion() == 'snapfish_eu' && _websiteInfo.getWebsiteName()!= 'snapfish_uk' )/* passing orientaion for intls sites */
            this.m_filteredThemes =  cardsGlobal.cardDesignsObj.filterCategory(cardsGlobal.selectedCategory, cardsGlobal.selectedSku, cardsGlobal.selectedPhotoCount, cardsGlobal.selectedParentCategory,cardsGlobal.selectedOrientation) ;
        else
            this.m_filteredThemes =  cardsGlobal.cardDesignsObj.filterCategory(cardsGlobal.selectedCategory, cardsGlobal.selectedSku, cardsGlobal.selectedPhotoCount, cardsGlobal.selectedParentCategory) ;
 
        // refreshing div references
        this.m_div = $(this.m_div.id);
        this.m_themeCountRangeDiv = $(this.m_themeCountRangeDiv.id);
        this.m_themeCountTotolDiv = $(this.m_themeCountTotolDiv.id);
        this.m_themeCountPageListDiv = $(this.m_themeCountPageListDiv.id);
        this.m_themeCountPageListDiv2 = $(this.m_themeCountPageListDiv.id+"2");
 
        this.m_totalThemeCount = this.m_filteredThemes.size();
        this.m_themeCountTotolDiv.innerHTML = this.m_totalThemeCount;
        this.m_totalPages = Math.ceil(this.m_totalThemeCount/this.m_defaultCount);
        // for single page
        if(this.m_totalPages <= 1){
            this.m_themeCountRangeDiv.innerHTML = this.m_totalThemeCount > 0 ? "1-"+this.m_totalThemeCount : "0";
            this.m_themeCountPageListDiv.innerHTML="";
            if(this.m_themeCountPageListDiv2) this.m_themeCountPageListDiv2.innerHTML="";
        }else{ // for multiple pages
            this.m_themeCountRangeDiv.innerHTML = "1-"+this.m_defaultCount;
            this.buildPageNumberList();
            this.clonePageNumberList();
        }
        this.renderThemesByPage();
    },
    renderThemesByPage : function(pageNumber){
        // this will render the themes page wise
 
        if(pageNumber == undefined) pageNumber = 1;
 
        if(pageNumber == 0){ // for view all
            CEventDispatcher.publish( "themeview" ,
            {"themesDataObject":this.m_filteredThemes,
            "selectedCategory" : cardsGlobal.selectedCategory,
            "photoFilter" : cardsGlobal.selectedPhotoCount,
            "sku":cardsGlobal.selectedSku } );
        }else{
            // filtering page wise themes
            var themeKeys = this.m_filteredThemes.keys();
            var themes = Hashtable.getInstance();
            for(var i = 0; themeKeys.hasMoreElements(); i++){ //i < this.m_totalThemeCount
                var themeKey = themeKeys.nextElement();
                var theme = this.m_filteredThemes.get(themeKey)
                if(i >= ((pageNumber-1) * this.m_defaultCount) && i < ((pageNumber)*this.m_defaultCount)){
                    themes.put(themeKey,theme);
                }
            }
            CEventDispatcher.publish( "themeview" ,
            {"themesDataObject":themes,
            "selectedCategory" : cardsGlobal.selectedCategory,
            "photoFilter" : cardsGlobal.selectedPhotoCount,
            "sku":cardsGlobal.selectedSku } );
        }
        if(this.m_totalPages > 1){
            this.refreshPageNumberList(pageNumber);
            this.m_currentPageNumber=pageNumber;
        }
    },
    buildPageNumberList : function(){
        // this will be created only once per selection.
        // first remove the existing pagination list
        while (this.m_themeCountPageListDiv.firstChild) {
            this.m_themeCountPageListDiv.removeChild(this.m_themeCountPageListDiv.firstChild);
        }
        //var _children = $(this.m_themeCountPageListDiv).childNodes ;
    //for(var i=0;i<_children.length;i++)
    //{
    //  $(this.m_themeCountPageListDiv).removeChild($(this.m_themeCountPageListDiv).childNodes[i]);
    //}
        var listDom = undefined;
        var anchorTag  = undefined;
        var lineDom = undefined;
        for(var i = 0 ; i < this.m_totalPages; i++){
 
            if(i+1 == 1){ // making first one is non clickable
                anchorTag = document.createTextNode(i+1);
            }else{
                anchorTag = document.createElement("a");
                anchorTag.setAttribute("href" , "javascript:showPage("+(i+1)+")");
                anchorTag.appendChild( document.createTextNode(i+1));
            }
            lineDom = document.createTextNode(" | ");
            listDom = document.createElement("span");
            listDom.setAttribute("id","page"+(i+1));
            listDom.appendChild(anchorTag);
            listDom.appendChild(lineDom);
            $(this.m_themeCountPageListDiv).appendChild(listDom);
        }
        // creating view all link by taking the innerhtml from view all div
        anchorTag = document.createElement("a");
        anchorTag.setAttribute("href" , "javascript:showPage(0)");
        anchorTag.appendChild( document.createTextNode(this.m_viewAllLinkText));
        listDom = document.createElement("span");
        listDom.setAttribute("id","page0");
        listDom.appendChild(anchorTag);
        $(this.m_themeCountPageListDiv).appendChild(listDom);
    },
    refreshPageNumberList : function(selectedNumber){
        // showing the range number like 13-24 for the count of 12
 
        if(selectedNumber == this.m_currentPageNumber) return;
 
        this.m_themeCountRangeDiv.innerHTML = selectedNumber == 0 ? ("1 - "+this.m_totalThemeCount) :
            (((selectedNumber-1) * this.m_defaultCount)+1)+"-"+((selectedNumber)*this.m_defaultCount > this.m_totalThemeCount ? this.m_totalThemeCount : (selectedNumber)*this.m_defaultCount);
 
        // adding anchor tag for the current number
        var currNumSpan = document.getElementById("page"+this.m_currentPageNumber);
        var numEle = currNumSpan.firstChild;
        var anchorTag = document.createElement("a");
        // creating an anchor element using the above number element text
        anchorTag.setAttribute("href" , "javascript:showPage("+this.m_currentPageNumber+")");
        anchorTag.appendChild(numEle.cloneNode(false/*recursive*/)) ; //reusing number element again to create the anchor tag
        currNumSpan.replaceChild(anchorTag,numEle);
        // removing anchor for selected number
        var newEleSpan = document.getElementById("page"+selectedNumber);
        anchorTag = newEleSpan.firstChild;
        text = anchorTag.innerHTML;
        newEleSpan.replaceChild(document.createTextNode(text),anchorTag);
 
        this.clonePageNumberList();
 
    },
    clonePageNumberList : function(){
        // bottom pagination list refreshing. just cloning the existing top pagination list and replacing the existing dom(first child of this div2).
        if(this.m_themeCountPageListDiv2){
            var clonedPageListNode = this.m_themeCountPageListDiv.cloneNode(true); // getting a cloned span element
            clonedPageListNode.removeAttribute("id");
            clonedPageListNode.childElements().each(function(spanEle){ spanEle.removeAttribute("id");}); // removing id attributes to avoid duplication with top pagination number ids
            if(this.m_themeCountPageListDiv2.firstChild){
                this.m_themeCountPageListDiv2.replaceChild(clonedPageListNode,this.m_themeCountPageListDiv2.firstChild /*first time it will be empty*/);
            }else{
                this.m_themeCountPageListDiv2.appendChild(clonedPageListNode);
            }
        }
    }
 
});
 
//--------------------------------------------------------------------------------------CLayoutPopupComponent
 
var CLayoutPopupComponent = Class.create({
 
  initialize : function(divId)
  {
      console.debug("CLayoutPopupComponent : div : "+divId);
    this.m_div = $(divId);
    this.m_body = $(divId+"Body");
    this.layoutObjectMap = Hashtable.getInstance();
    this.status = false; // hidden
    this.theme = undefined; // will be set in CCategoryViewComponent, FIX ME: need to avoid this
  } , // end of init
  subscribe : function(topicName)
    {
        console.debug("CLayoutPopupComponent : subscribing to : "+topicName);
      CEventDispatcher.subscribe( topicName , this , this.renderLayouts );
    } ,
 
  renderLayouts : function( dataObject/*Theme Layout Data Obect*/ ,themeDisplayName)
  {
    this.layoutObjectMap = Hashtable.getInstance();
 
      console.debug("CLayoutPopupComponent : renderLayouts  : dataObject : "+dataObject);
 
        // building layouts dom before adding to main div
 
        var layoutsTable = document.createElement("TABLE"); // for IE
        var layoutsTBody = layoutsTable.appendChild(document.createElement("TBODY")); // for IE
 
    var skuMap = dataObject;
 
    var skuKeys = skuMap.keys();
      var noLayouts = true;
        for(var i = 0,row = 0; skuKeys.hasMoreElements(); i++){
        var skuName = skuKeys.nextElement();
        var layoutsBySku = skuMap.get(skuName);
 
        var layoutsTd = layoutsTBody.insertRow(row++).insertCell(0);
        console.debug("CLayoutPopupComponent : renderLayouts  :sku Name : "+skuName +" , no of layouts  : "+layoutsBySku.length);
 
        var tableEle = document.createElement("TABLE"); // for IE
        var tBodyEle = tableEle.appendChild(document.createElement("TBODY")); // for IE
        var trEle = tBodyEle.insertRow(0);
        for(var j = 0,k = 0,l = 0 ; j < layoutsBySku.length; j++){
            var layoutObj = layoutsBySku[j];
                var tdEle = trEle.insertCell(k++);
                tdEle.setAttribute("valign","bottom");
                tdEle.setAttribute("style","padding-bottom:20px;");
            var iconUrl = layoutObj.iconurl;
            if(iconUrl && iconUrl.length > 2048 && isIE ){ // to solve rendered image loading in IE for long urls
 
                var start = iconUrl.indexOf("/MONTAGE_OUTPUT=");
                var end = iconUrl.indexOf("/",start+1);
                var wh = iconUrl.substring(start+"/MONTAGE_OUTPUT=".length,end); // ex : 158x102
                wh = wh.split("x");
 
                selfLoadUrl = getSelfLoadUrl(iconUrl);
                var iFrameHtml = "<iframe src='"+selfLoadUrl+"' width='"+wh[0]+"' height='"+wh[1]+"' frameborder='no'    border='1'    marginwidth='0'   marginheight='0'   scrolling='no'>";
                tdEle.innerHTML = iFrameHtml ;
            }else{
                var imgNode = new Element("img", {'src':iconUrl,'title':themeDisplayName,'style':"float:left;margin-left:10px;"});
                tdEle.appendChild(imgNode);
            }
 
            if(k == 4){ // 4 cells per row, after that adding new row
                k = 0; l++;
                trEle = tBodyEle.insertRow(l);
            }
            noLayouts = false;
        }
        layoutsTd.appendChild(tableEle);
        if(skuKeys.hasMoreElements()){
            var lineTd = layoutsTBody.insertRow(row++).insertCell(0);
            lineTd.setAttribute("style","border-top:1px dashed #75D23B;height:10px;padding-left:10px;");
            //lineTd.addClassName("green-doted-line");
            lineTd.innerHTML = "<img src='"+spacerImg+"' height=1/>";
        }
    }
 
    // regaining the references
    this.m_body = $(this.m_body.id);
    this.m_div = $(this.m_div.id);
 
    // removing existing child nodes from main div
    while (this.m_body.firstChild) {
        this.m_body.removeChild(this.m_body.firstChild);
        }
 
        if(noLayouts){
            layoutsTBody.insertRow(0).insertCell(0).innerHTML = noLayoutsText;
        }
    // adding layouts table to existing main div
    this.m_body.appendChild(layoutsTable);
 
    return ;
  },  // end of renderLayouts
  hide: function(){
        this.status = false;
    $(this.m_div.id).hide();
    // removing existing child nodes from main div
    this.m_body = $(this.m_body.id);
    while (this.m_body.firstChild) {
        this.m_body.removeChild(this.m_body.firstChild);
        }
  },
  show: function(theme){
    this.locate(theme);
    $(this.m_div.id).show();
    $(this.m_body.id).appendChild(document.createTextNode(loadingText));
    this.status = true;
  },
 
  locate : function(theme){
            var pos = $(theme).positionedOffset();
            pos.top += $(theme).getHeight();
            $(this.m_div.id).setStyle({position:"absolute",left : pos.left+80, top : pos.top-35});
  }
 
});// end of class
//--------------------------------------------------------------------------------------CLayoutPopupComponent
//SizeSkuMap = {"4x8":"photocard4x8","5x7":"photocard5x7"};
 
var CLayoutSelectionComponent = Class.create({
 
  initialize : function(table,sku)
  {
      console.debug("CLayoutSelectionComponent : table : "+table);
    this.m_table = $(table) ;
    this.sku = sku;
    this.theme = undefined; // will be set in CCategoryViewComponent, FIX ME: need to avoid this
    this.active = true;
  } , // end of init
  subscribe : function(topicName)
    {
 
        console.debug("CLayoutSelectionComponent : subscribing to : "+topicName);
      CEventDispatcher.subscribe( topicName , this , this.renderLayouts );
    } ,
 
  renderLayouts : function( dataObject/*Theme Layout Data Obect*/ )
  {
      console.debug("CLayoutSelectionComponent : renderLayouts  : dataObject : "+dataObject);
 
        // removing existing child nodes from main div
        this.m_table = $(this.m_table.id);
    while (this.m_table.firstChild) {
        this.m_table.removeChild(this.m_table.firstChild);
        }
 
    var tBody = this.m_table.appendChild(document.createElement("TBODY")); // for IE
        var layoutsTr = tBody.insertRow(0);
 
    var skuMap = dataObject;
 
        var layoutsBySku = skuMap.get(this.sku);
        if(layoutsBySku){
        for(var j = 0 ; j < layoutsBySku.length; j++){
                var layoutObj = layoutsBySku[j];
            var layoutKey = layoutObj.templatename;
            var photoCount = layoutObj.userphotos.length;
            var greetingCount=0;
            for(var k=0;k<photoCount;k++)
            {
                var isGreeting =(layoutObj.userphotos[k]).is_greeting;
                if(isGreeting!="undefined" && isGreeting=="true")
                    greetingCount=greetingCount+1;
 
            }
            photoCount=photoCount-greetingCount;
            if(typeof isPhotoCountDisplaySupported != "undefined" && isPhotoCountDisplaySupported=="false"){
          	  photoCount = "";
            }else{
              photoCount = parseInt(photoCount) == 1 ? photoCount+" "+photoText : photoCount+" "+photosText;
            }
                var orientation = layoutObj.orientation;
                orientation = orientation.substring(0,orientation.indexOf(".xml"));
            var skuLayoutTd = new Element("td", {"id":this.sku+"_"+layoutKey+"_"+orientation+"_Td","valign":"bottom","align":"center","class":"img_unselect", "width":"55"});
            var anchorTag = new Element("a",{"href":"javascript:selectLayout('"+this.sku+"','"+layoutKey+"','"+orientation+"')"});
            var themeImage = null;
            var iconUrl=layoutObj.iconurl;
            var paddingTop = orientation == "landscape" ? 70 : 0;
            var iconWidth=0; var iconHeight = 0;
            if(iconUrl != null){
                var start = iconUrl.indexOf("/MONTAGE_OUTPUT=");
                var end = iconUrl.indexOf("/",start+1);
                var wh = iconUrl.substring(start+"/MONTAGE_OUTPUT=".length,end); // ex : 158x102
                wh = wh.split("x");
                iconWidth = wh[0]; iconHeight = wh[1];
                paddingTop = 100 - (isNaN(wh[1])? 0 : wh[1]);
            }
            if(iconUrl && iconUrl.length > 2048 && isIE){ // to solve image loading in IE for long urls
            selfLoadUrl = getSelfLoadUrl(iconUrl);
            themeImage = new Element("div");
               var iFrameHtml = "<div style='position:absolute;z-index:100;height:"+iconHeight+"px;width:"+iconWidth+"px'>"+
                "<a href=\"javascript:selectLayout('"+this.sku+"','"+layoutKey+"','"+orientation+"')\"><img src='"+spacerImg+"' width='"+iconWidth+"' height='"+iconHeight+"' style='cursor:hand'></img></a></div>"+
                "<div style='height:"+iconHeight+"px;width:"+iconWidth+"px'>"+
                "<iframe src='"+selfLoadUrl+"' border='"+0+"' width='"+iconWidth+"' height='"+iconHeight+"' frameborder='no'    marginwidth='0'   marginheight='0'   scrolling='no'></iframe></div>";
            themeImage.innerHTML = iFrameHtml ;
            }else{
                themeImage = new Element("img", {'src':layoutObj.iconurl,'title':chooseThisLayoutText});
            }
            anchorTag.appendChild( themeImage ); skuLayoutTd.appendChild(anchorTag);
            if(!(iconUrl && iconUrl.length > 2048 && isIE))
            skuLayoutTd.appendChild(document.createElement("br"));
            skuLayoutTd.appendChild(document.createTextNode(photoCount));
            layoutsTr.appendChild(skuLayoutTd);
            // window scope call
            if(cardsGlobal.selectedLayout == undefined){
                if(this.sku == cardsGlobal.selectedSku && cardsGlobal.selectedOrientation == orientation ){
                    selectLayout(this.sku,layoutKey,orientation);
                }
            }
        }
        }else{
                var skuLayoutTd = new Element("td", {"id":layoutKey,"valign":"bottom","align":"left","class":"img_unselect"});
            skuLayoutTd.appendChild(document.createTextNode(noLayoutsText));
            layoutsTabContainer.hideTab(this.sku);
            layoutsTr.appendChild(skuLayoutTd);
            this.active = false;
        }
      //    var skuKeys = skuMap.keys();
    //for(var i = 0; skuKeys.hasMoreElements(); i++){
    //  var skuName = skuKeys.nextElement();
    //}
 
    return ;
  }
 
});// end of class
 
//--------------------------------------------------------------------------------------CFeaturedCategoryViewComponent
 
var CFeaturedCategoryViewComponent = Class.create({
  initialize : function(table,showNameLink,showPhotoCount,showSku)
  {
    this.m_table = $(table) ;
    this.showPhotoCount = showPhotoCount ? showPhotoCount : false;
    this.showName = showNameLink ? showNameLink : false;
    this.showSku = showSku ? showSku : false;
    //this.showSelection = false;
  } , // end of init
  subscribe : function(topicName)
    {
      CEventDispatcher.subscribe( topicName , this , this.renderThemes );
    } ,
 
  renderThemes : function( dataObject/*Featured Themes Data Obect*/ )
  {
    var themesDataObject =  dataObject.getFeaturedThemes();
    var themeKeys = themesDataObject.keys() ;
      /* To fix WG0007409*/
        var featuredCategoryName = cardsGlobal.cardDesignsObj.getDefaultCategory();
		 if( _websiteInfo.getWebsiteName() == "walgreens_us" || _websiteInfo.getWebsiteName() == "walmart_us")
			featuredCategoryName = cardsGlobal.cardDesignsObj.getDefalutlCategoryDisplayName();
    if(cardsGlobal.hasFeatured)
        featuredCategoryName = "featured";
        // removing existing child nodes from main div
    while (this.m_table.firstChild) {
        this.m_table.removeChild(this.m_table.firstChild);
        }
    var tBody = this.m_table.appendChild(document.createElement("TBODY")); // for IE browser
    var themesTr = tBody.insertRow(0);
    var aboutFoldedCardsPageHeading = featuredCategoryName + " Designs";
    var element = document.getElementById("aboutFoldedCardsPageHeading");
    if(element!=undefined){
    element.innerHTML = aboutFoldedCardsPageHeading;
    }
    if(!themesDataObject || themesDataObject.size() == 0){
         var themeTd = new Element("td",{"align":"center","style":"padding-left:20px;"});
         themeTd.innerHTML = noThemesText;//"No Featured Themes available for this Size.";
         themesTr.appendChild(themeTd);
         return;
    }
 
 
    while(themeKeys.hasMoreElements())    {
      var themeKey = themeKeys.nextElement();
      console.debug("CFeaturedCategoryViewComponent : renderThemes : themeKey : "+themeKey);
      var oTheme = themesDataObject.get(themeKey) ;
            var sku = cardsGlobal.selectedSku;
            sku = sku == "all" ? oTheme.getDefaultSku() : sku;
            var orientationBySku = cardsGlobal.cardDesignsObj.getDefaultOrientation(sku);
            var displayName = oTheme.getDisplayName();
            displayName = displayName == "null" ? oTheme.getDisplayName() : displayName;
            var iconObj = oTheme.getIconUrl(sku);
      var iconUrl = oTheme.getIconUrl(sku).get("featured_design_"+orientationBySku);
      if(iconUrl == undefined || iconUrl == null)
      {
          orientationBySku = (orientationBySku == 'landscape'? 'portrait' :'landscape');
          iconUrl = oTheme.getIconUrl(sku).get("featured_design_"+orientationBySku);
      }
      // iconUrl = iconUrl ? iconUrl : oTheme.getIconUrl(sku).get(orientationBySku); // if not featured image, take the default
      iconUrl = iconUrl ? iconUrl : oTheme.getThemeIconUrl(sku, orientationBySku, 1, true);
      if(iconUrl == undefined && iconObj.size() == 2){
            orientationBySku = iconObj.keys().nextElement();
            iconUrl = oTheme.getIconUrl(sku).get("featured_design_"+orientationBySku);
      }
 
      var themeTd = new Element("td",{"align":"center","style":"padding-top:10px;"});
      var local_isStockings = (window.photoStockingsLarge == sku || window.photoStockingsSmall == sku);
      var stockingsDiv = new Element("div",{"style":"border:solid 1px #dddddd;width:89px; height:88px;padding-top:3px;" });
      var themeImage = null;
      if(iconUrl && iconUrl.length > 2048 && isIE){ // to solve rendered image loading in IE for long urls
        selfLoadUrl = getSelfLoadUrl(iconUrl);
        var themeImage = new Element("div");
 
        var start = iconUrl.indexOf("/MONTAGE_OUTPUT=");
        var end = iconUrl.indexOf("/",start+1);
        var wh = iconUrl.substring(start+"/MONTAGE_OUTPUT=".length,end); // ex : 158x102
 
        wh = wh.split("x");
 
        var iFrameHtml = "<div style='position:absolute;z-index:100;height:"+wh[1]+"px;width:"+wh[0]+"px'>"+
                "<a href=\"JavaScript:hideThemeLayouts();showLayoutsPage('"+themeKey+"','"+orientationBySku+"','"+sku+"','"+featuredCategoryName+"')\"><img src='"+spacerImg+"' width='"+wh[0]+"' height='"+wh[1]+"' style='cursor:hand'></img></a></div>"+
                "<div style='solid;height:"+wh[1]+"px;width:"+wh[0]+"px'>"+
            "<iframe src='"+selfLoadUrl+"' width='"+wh[0]+"' height='"+wh[1]+"'  frameborder='no'    border='1'    marginwidth='0'   marginheight='0'   scrolling='no'></iframe></div>";
 
        if((window.photocard4x8 == sku  || window.photocard4x8st == sku || window.photocard5x7 == sku || window.photocard5x7st == sku)
           && _websiteInfo.getRegion() == 'snapfish_eu' && _websiteInfo.getWebsiteName()!= 'snapfish_uk' ){
           themeURLIndex = setThemeIDArray(encodeURI(iconUrl));
           iFrameHtml = "<div style='position:absolute;z-index:100;height:"+wh[1]+"px;width:"+wh[0]+"px'>"+
                "<a href=\"JavaScript:hideThemeLayouts();showLayoutsPage('"+themeKey+"','"+orientationBySku+"','"+sku+"', undefined,'"+themeURLIndex+"')\"><img src='"+spacerImg+"' width='"+wh[0]+"' height='"+wh[1]+"' style='cursor:hand'></img></a></div>"+
                "<div style='solid;height:"+wh[1]+"px;width:"+wh[0]+"px'>"+
            "<iframe src='"+selfLoadUrl+"' width='"+wh[0]+"' height='"+wh[1]+"'  frameborder='no'    border='1'    marginwidth='0'   marginheight='0'   scrolling='no'></iframe></div>";
         }
        themeImage.innerHTML = iFrameHtml ;
      }else{
        if(local_isStockings){
          if(window.photoStockingsLarge == sku)
            themeImage = new Element("img",{"src":iconUrl,"title":displayName,"style":"padding-left:5"});
          else
            themeImage = new Element("img",{"src":iconUrl,"title":displayName});
        }
        else{
          themeImage = new Element("img",{"src":iconUrl,"title":displayName});
        }
      }
 
      var anchorTag = new Element("a",{"href":"JavaScript:hideThemeLayouts();showLayoutsPage('"+themeKey+"','"+orientationBySku+"','"+sku+"','"+featuredCategoryName+"');"});
       if((window.photocard4x8 == sku  || window.photocard4x8st == sku || window.photocard5x7 == sku || window.photocard5x7st == sku)
           && _websiteInfo.getRegion() == 'snapfish_eu' && _websiteInfo.getWebsiteName()!= 'snapfish_uk' ){
           themeURLIndex = setThemeIDArray(encodeURI(iconUrl));
           anchorTag = new Element("a",{"href":"JavaScript:hideThemeLayouts();showLayoutsPage('"+themeKey+"','"+orientationBySku+"','"+sku+"', undefined,'"+themeURLIndex+"');"});
         }
 
if(local_isStockings){
 
 
        //anchorTag.appendChild(whiteCuffImgDiv) ;
        var whiteCuffImg = new Element("img",{"class":"small_stockingcuff","src":"/default/images/walmart/walmart_us/stockings/create_stocking_cuff.jpg"});
        if(window.photoStockingsLarge == sku)
          whiteCuffImg = new Element("img",{"class":"large_stockingcuff","src":"/default/images/walmart/walmart_us/stockings/create_stocking_cuff.jpg"});
        var whiteCuffImgDiv = new Element("div");
        whiteCuffImgDiv.appendChild(whiteCuffImg);
        stockingsDiv.appendChild(whiteCuffImgDiv);
        stockingsDiv.appendChild(themeImage);
        anchorTag.appendChild( stockingsDiv ) ;
}else{
      anchorTag.appendChild( themeImage ) ;
}
      if(window.notebook9x6 == sku && (sku.toLowerCase().indexOf("notebook")>=0) && !('notepads'==sku || 'Stickersx48'==sku || 'Tag;luggage'== sku)){
        var spiralImg = new Element("img",{
                "src":"/default/images/notebooks/about_ring.png",
                "style":"position: relative; top: -1px; left: -60px; z-index: 1;"
        });
        anchorTag.appendChild(spiralImg) ;
 
        $(themeImage).setStyle({
            position: "relative",
            zIndex: "0",
            left: "3px"
        });
      }
      if(window.walmartJournal == sku){
 
        var spiralImg = new Element("img",{
                "src":"/default/images/walmart/walmart_us/journals/about_journal_spine.gif",
                "style":"position: relative; top: -1px; left: -69px; z-index: 1;"
        });
        anchorTag.appendChild(spiralImg) ;
 
        $(themeImage).setStyle({
            position: "relative",
            zIndex: "0",
            left: "3px"
        });
      }
 
      themeTd.appendChild(anchorTag);
      if(this.showName || this.showSku || this.showPhotoCount){
          // this is for Text if any:
          var themeTextDiv = new Element("div",{"style":"width:150px; padding-top:5px;"});//,{"style":"line-height:16px"}
          if(this.showName){
              anchorTag = new Element("a",{"href":"javascript:hideThemeLayouts();showLayoutsPage('"+themeKey+"','"+orientationBySku+"','"+sku+"','"+featuredCategoryName+"');"});
              if((window.photocard4x8 == sku  || window.photocard4x8st == sku || window.photocard5x7 == sku || window.photocard5x7st == sku)
                         && _websiteInfo.getRegion() == 'snapfish_eu' && _websiteInfo.getWebsiteName()!= 'snapfish_uk' ){
                         themeURLIndex = setThemeIDArray(encodeURI(iconUrl));
                                 anchorTag = new Element("a",{"href":"JavaScript:hideThemeLayouts();showLayoutsPage('"+themeKey+"','"+orientationBySku+"','"+sku+"', undefined,'"+themeURLIndex+"');"});
                   }
              if( _websiteInfo.getWebsiteName() == "walgreens_us")
                displayName = displayName.length > 22 ? displayName.substring(0,22)+" ..." : displayName;
              else if(_websiteInfo.getWebsiteName() == "walmart_us")
            	  displayName = displayName;
              else
                displayName = displayName.length > 25 ? displayName.substring(0,25)+"<br/>"+displayName.slice(25) : displayName;
              if( _websiteInfo.getWebsiteName() == "walmart_us" && window.addresslabel == sku)
                                anchorTag.innerHTML = initCaps(displayName);
                          else
                                anchorTag.innerHTML = displayName;
              themeTextDiv.appendChild(anchorTag);
              themeTextDiv.appendChild(document.createElement("br"));
            }
 
                if(this.showSku){
                   if(_websiteInfo.getWebsiteName() == "walmart_us"){
                    if(!cardsGlobal.isStationery){
                        if(oTheme.getDisplayText() == "4 x 8" && (upc==null || upc == "" || upc == "null") && cardNametext4x8!=""){
                            cardNameText = cardNametext4x8;
                        }else if(oTheme.getDisplayText() == "5 x 7" && (upc==null || upc == "" || upc == "null") && cardNametext5x7!=""){
                            cardNameText = cardNametext5x7;
                        }
                    }else{
                        if(oTheme.getDisplayText() == "4 x 8" && (upc==null || upc == "" || upc == "null") && cardNametext4x8st!=""){
                            cardNameText = cardNametext4x8st;
                        }else if(oTheme.getDisplayText() == "5 x 7" && (upc==null || upc == "" || upc == "null") && cardNametext5x7st!=""){
                            cardNameText = cardNametext5x7st;
                        }
 
                    }
                    if(local_isStockings)
                     cardNameText = "Stocking";
                var displayTextNode = document.createTextNode(cardNameText);
              }else{
                var displayTextNode = document.createTextNode((window.notebook9x6 == sku && _websiteInfo.getWebsiteName() == 'snapfish_uk') ? notebooksDisplayText :
                                                                                                                oTheme.getDisplayText()+" "+cardNameText);
                if(_websiteInfo.getRegion() == 'snapfish_eu' && _websiteInfo.getWebsiteName()!= 'snapfish_uk')
                                displayTextNode=document.createElement("br");
              }
              themeTextDiv.appendChild(displayTextNode);
          }
 
          if(this.showPhotoCount){
              var formattedCountNode = document.createTextNode(oTheme.getFormattedCount());
              themeTextDiv.appendChild(formattedCountNode);
              themeTextDiv.appendChild(document.createElement("br"));
          }
          themeTd.appendChild(themeTextDiv);
      }
      themesTr.appendChild(themeTd);
    }// ened of while
    return ;
  }  // end of renderThemes
});// end of class
 
function showPage(pageNumber){
        if(oLayoutPopupComponent.status){
        oLayoutPopupComponent.hide();
    }
    oThemePaginationComponent.renderThemesByPage(pageNumber);
}
 
function filterBySku(event){
    hideThemeLayouts();
 
    var element = Event.element(event);
    var sku = element.value;
    //alert(sku);
    console.debug("filterBySku : publish : for sku :  "+sku);
    cardsGlobal.selectedSku = sku;
    //cardsGlobal.selectedCategory = undefined; // as therse will be rebuild
    //var category = cardsGlobal.selectedCategory ? cardsGlobal.selectedCategory : cardsGlobal.cardDesignsObj.getDefaultCategory();
    //var photoCountFilter = cardsGlobal.selectedPhotoCount ? cardsGlobal.selectedPhotoCount : cardsGlobal.cardDesignsObj.getDefaultFilter();
 
    CEventDispatcher.publish( "sizechanged" ,{} );
    $("MoreOccationsPopup").hide(); // to hide if open
 
    if(oFeaturedCategoryViewComponent){ // refreshing the featured themes for the selected sku
        oFeaturedCategoryViewComponent.renderThemes(cardsGlobal.cardDesignsObj);
    }
}
 
function filterByPhotoCount(event){
    hideThemeLayouts();
 
    var element = Event.element(event);
    var count = element.value;
    //alert(count);
    console.debug("filterByPhotoCount : publish : for count :  "+count);
    cardsGlobal.selectedPhotoCount = count;
    //var category = cardsGlobal.selectedCategory ? cardsGlobal.selectedCategory : cardsGlobal.cardDesignsObj.getDefaultCategory();
    //var sku = cardsGlobal.selectedSku ? cardsGlobal.selectedSku : cardsGlobal.cardDesignsObj.getDefaultSku();
 
    CEventDispatcher.publish( "categoryview" ,{} );
}
 
 
 
function filterByOrientation(){
    var event = arguments[0]||window.event;
    var element=event.srcElement || event.target;
    var selectedOrientation = element.value;
    cardsGlobal.selectedOrientation = selectedOrientation;
    CEventDispatcher.publish( "categoryview" ,{} );
}
 
function filterByCategory(category, categoryParent){
 
    //var sku = cardsGlobal.selectedSku ? cardsGlobal.selectedSku : cardsGlobal.cardDesignsObj.getDefaultSku();
    //var photoCountFilter = cardsGlobal.selectedPhotoCount ? cardsGlobal.selectedPhotoCount : cardsGlobal.cardDesignsObj.getDefaultFilter();
 
    //if themelayouts popup is displaying hide it
    hideThemeLayouts();
 
    console.debug("filterByCategory : publish : for category:"+category+"; categoryParent:"+categoryParent);
    category = CURLDecoder.decode(category);
    CEventDispatcher.publish( "categoryselection" ,  {"selectedCategory" : category, "categoryParent" : categoryParent} );
    CEventDispatcher.publish( "categoryview" ,  {"selectedCategory" : category, "categoryParent" : categoryParent} );
    if(dojo.byId('catName')){
        var catDisplayName=cardsGlobal.cardDesignsObj.getCategory(category,cardsGlobal.selectedSku).getDisplayName();
        if(catDisplayName)
        dojo.byId('catName').innerHTML=catDisplayName;
        else dojo.byId('catName').innerHTML=selectedCategory;
        if(typeof trackNav != 'undefined')trackNav(dojo.byId(category+'Link'),catDisplayName);
    }
}
 
function showThemeLayouts(theme,orientation){
    //if(oLayoutPopupComponent.status) return; // ignore if already showing
        if(oLayoutPopupComponent.status){
        oLayoutPopupComponent.hide();
    }
    oLayoutPopupComponent.show(theme); // event
    if(window.s && window.s_account)
        prevSPageName = s.pageName;
    loader.omnitureTrack({"sPageName":selectDesignsSPagename+" Layout Layer"});
 
    console.debug("showThemeLayouts : themeName :"+oLayoutPopupComponent.theme);
    CEventDispatcher.publish( "loadthemelayouts" ,{"theme":theme,"url":getSelectedThemeLayoutUrl(theme,orientation)} )
}
function hideThemeLayouts(){
    console.debug("hidingThemeLayouts.");
    if(oLayoutPopupComponent.status)
    {
        oLayoutPopupComponent.hide();
        // resetting to old values
        if(prevSPageName) loader.omnitureTrack({"sPageName":prevSPageName});
    }
}
// ------------------------------------------------cards_designs.jsp related script--------------------------------------------
 
oOccasionsTreeViewComponent = undefined;
oThemePaginationComponent=undefined;
oLayoutPopupComponent=undefined;
oSizeViewComponent = undefined;
oPhotoFilterViewComponent = undefined;
oCardsDesignsDataComponent = undefined;
oFeaturedCategoryViewComponent = undefined;
 
oCardsThemeLayoutDataComponent=undefined;
themesPerPage=12;//defaultCount; override this in jsp if you want more/less.
view_all_text='view all'; //this gets overriden in Intl jsp.
 
cardsdesignsSubscribe = function(designDataUrl,selectedCategory){
        dataLoadingInProgress=true;
        // this is to avoid repeated subscription.
        if(selectedCategory != "null")
            {
                cardsGlobal.selectedCategory = selectedCategory;
               // cardsGlobal.selectedParentCategory = categoryParent;
            }
        if(cardsGlobal.isCardsdesignsSubscribed){
            cardsGlobal.cardDesignsJsonDataObj = undefined;
            cardsGlobal.cardDesignsObj = undefined;
            if(oCardsDesignsDataComponent)
                 oCardsDesignsDataComponent.setUrl(designDataUrl);
            return;
        }
        cardsGlobal.isCardsdesignsSubscribed = true;
 
        oPhotoFilterViewComponent = new CPhotoFilterViewComponent('PhotoFilterDiv');
        oPhotoFilterViewComponent.subscribe('datachanged');
 
        oSizeViewComponent = new CSizeViewComponent('SizeDiv');
        oSizeViewComponent.subscribe('datachanged');
 
        oOccasionsTreeViewComponent = new COccasionsTreeViewComponent('OccasionsDiv', cardsGlobal.selectedCategory, cardsGlobal.selectedParentCategory);
        oOccasionsTreeViewComponent.subscribe('sizechanged');
        CEventDispatcher.subscribe( "categoryselection" , oOccasionsTreeViewComponent , oOccasionsTreeViewComponent.setSelection );
 
        //CEventDispatcher.subscribe("datachanged",window,showSelectDesignsPage );
 
        oCategoryViewComponent = new CCategoryViewComponent('CategoryDiv');
        oCategoryViewComponent.subscribe('themeview');
 
        oThemePaginationComponent = new CThemePaginationComponent('ThemeCountDiv',
        "ThemeCountRangeDiv","ThemeCountTotolDiv","ThemeCountPageListDiv",view_all_text,themesPerPage)
        oThemePaginationComponent.subscribe('categoryview');
 
        oLayoutPopupComponent= new CLayoutPopupComponent('LayoutPopup');
        oLayoutPopupComponent.subscribe('loadedthemelayouts');
 
        oCardsThemeLayoutDataComponent = new CCardsThemeLayoutDataComponent('loadedthemelayouts');
        oCardsThemeLayoutDataComponent.subscribe('loadthemelayouts');
 
    oCardsDesignsDataComponent = new CCardsDesignsDataComponent(designDataUrl, 'datachanged');
    oCardsDesignsDataComponent.subscribe('windowload');
 
}
function showSelectDesignsPage(){
    $("SelectDesign").show();
}
function showMoreLayer(){
    var morePopup = $("MoreOccationsPopup");
    if(morePopup.visible()){
        morePopup.hide();
        // resetting to old values
        if(prevSPageName) loader.omnitureTrack({"sPageName":prevSPageName});
    }else{
        morePopup.show();
 
        if(window.s && window.s_account)
           prevSPageName = s.pageName;
 
        loader.omnitureTrack({"sPageName":moreLayerSPageName});
    }
}
 
function captureOnClickEvent(e){
    if(navigator.appName == "Microsoft Internet Explorer"){
        cardsGlobal.onClickX = event.clientX;
        cardsGlobal.onClickY = event.clientY;
      }else {
        cardsGlobal.onClickX = e.pageX;
        cardsGlobal.onClickY = e.pageY;
      }
      //alert("Click at x = " +cardsGlobal.onClickX+ " and y = " + cardsGlobal.onClickY);
}
 
// will be called form self_load_renderer_ifram.jsp to get the long( >2048) url to load rendered images in IE
function getRenderingUrlForPage(){
    if( ( (_websiteInfo.getRegion() == 'snapfish_eu' && _websiteInfo.getWebsiteName()!= 'snapfish_uk') || _websiteInfo.getWebsiteName() == "walmart_us"
        || _websiteInfo.getWebsiteName() == "walgreens_us" )  && typeof bigURLList != 'undefined' && arguments[2] != null && arguments[2] != 'null'){
        return bigURLList[arguments[2]];
    }
    return selfLoadImageUrl;
}
 
// this is to get modified rendered host url to load the long lenth image urls( above 2048)
function getSelfLoadUrl(iconUrl){
 
    selfLoadImageUrl = iconUrl;
    if(selfLoadUrl.indexOf('?renderhost=') == -1){
        var renderHost = iconUrl.split("render/");
        renderHost = renderHost.length > 1 ? renderHost[0]+"render/" : "render/";
        selfLoadUrl = selfLoadUrl + "?renderhost=" + renderHost ;
    }
    //this selfload behaviour is broken with mutliple iframe requests,hence writing the below......
    if( ( (_websiteInfo.getRegion() == 'snapfish_eu' && _websiteInfo.getWebsiteName()!= 'snapfish_uk') || _websiteInfo.getWebsiteName() == "walmart_us"
        || _websiteInfo.getWebsiteName() == "walgreens_us" )  && typeof bigURLList != 'undefined') {
        bigURLList[imgCount]=iconUrl;
        if(selfLoadUrl.indexOf("imgCount=") == -1){
            if(selfLoadUrl.indexOf('?') != -1 )
                selfLoadUrl = selfLoadUrl + "&imgCount="+imgCount;
            else
                selfLoadUrl = selfLoadUrl + "?imgCount="+imgCount;
        }else{
             selfLoadUrl = selfLoadUrl.replace(/imgCount=\d+/g,"imgCount="+imgCount);
        }
        imgCount++;
    }
    return selfLoadUrl;
}
document.onclick =  captureOnClickEvent;
 
// ------------------------------------------------cards_layouts.jsp related script--------------------------------------------
oCardsThemeLayoutDataComponent = undefined;
 
layoutSelectionPage4x8 = undefined;
layoutSelectionPage5x7 = undefined;
layoutSelectionPage8x8 = undefined;
layoutSelectionPage8x10 = undefined;
layoutSelectionPage12x12 = undefined;
layoutSelectionPageCharater4x8 = undefined;
 
cardslayoutsSubscribe = function(layoutDataUrl){
        // this is to avoid repeated subscription.
 
 
        if(cardsGlobal.isCardsLayoutsSubscribed){
            oCardsThemeLayoutDataComponent.setUrl(layoutDataUrl);
            return;
        }
 
        cardsGlobal.isCardsLayoutsSubscribed = true;
 
        if(document.getElementById("photocard5x7LayoutsTable")!=undefined){
        layoutSelectionPage5x7 = new CLayoutSelectionComponent("photocard5x7LayoutsTable",photocard5x7);
      layoutSelectionPage5x7.subscribe('layoutselectionview');
        }
      if(document.getElementById("photocard4x8LayoutsTable")!=undefined){
        layoutSelectionPage4x8 = new CLayoutSelectionComponent("photocard4x8LayoutsTable",photocard4x8);
        layoutSelectionPage4x8.subscribe('layoutselectionview');
       } if(document.getElementById("scrapbookpage8x8LayoutsTable")!=undefined){
        layoutSelectionPage8x8 = new CLayoutSelectionComponent("scrapbookpage8x8LayoutsTable",scrapbookpage8x8);
      layoutSelectionPage8x8.subscribe('layoutselectionview');
      }
 
      if(document.getElementById("scrapbookpage8x10LayoutsTable")!=undefined){
         layoutSelectionPage8x10 = new CLayoutSelectionComponent("scrapbookpage8x10LayoutsTable",scrapbookpage8x10);
      layoutSelectionPage8x10.subscribe('layoutselectionview');
        }
        if(document.getElementById("scrapbookpage12x12LayoutsTable")!=undefined){
         layoutSelectionPage12x12 = new CLayoutSelectionComponent("scrapbookpage12x12LayoutsTable",scrapbookpage12x12);
      layoutSelectionPage12x12.subscribe('layoutselectionview');
        }
      if(document.getElementById("WMCharacterCards;photocard4x8LayoutsTable")!=undefined){
        layoutSelectionPageCharater4x8 = new CLayoutSelectionComponent("WMCharacterCards;photocard4x8LayoutsTable",charactercard4x8);
        layoutSelectionPageCharater4x8.subscribe('layoutselectionview');
       }
        CEventDispatcher.subscribe("layoutselectionview", window , setLayoutsText) ;
 
      oCardsThemeLayoutDataComponent = new CCardsThemeLayoutDataComponent('layoutselectionview');
      oCardsThemeLayoutDataComponent.subscribe('loadlayoutsdata');
}
setLayoutsText = function(dataObject){
    /*if(dataObject.size() == 2){
        $("available_photocard4x8_photocard5x7_text").show();
    }else{
        var key = dataObject.keys().nextElement();
        $("available_"+key+"_text").show();
    }*/
     var keySet = dataObject.keys();
    var key = "_";
    var key1 = "";
    var key2 = "";
    while(keySet.hasMoreElements()){
    key1 = key+keySet.nextElement();
    key2 = key2 +key1;
    }
    $("available"+key2+"_text").show();
}
selectLayout = function(sku,layoutId,orientation){
        var td = $(sku+"_"+layoutId+"_"+orientation+"_Td");
        if(cardsGlobal.selectedLayout == layoutId && selectedLayoutSize && selectedLayoutSize == sku && cardsGlobal.selectedOrientation == orientation) return;
        if(cardsGlobal.selectedLayout){
            var selectedTd = $(selectedLayoutSize+"_"+cardsGlobal.selectedLayout+"_"+cardsGlobal.selectedOrientation+"_Td");
            selectedTd.removeClassName("img_select");
            selectedTd.addClassName("img_unselect");
        }
        td.removeClassName("img_unselect");
        td.addClassName("img_select");
        var layoutObject  = oCardsThemeLayoutDataComponent.getLayoutObject(sku,layoutId,orientation);
        if(layoutObject){
            //orientation = layoutObject.orientation;
            //orientation = orientation.substring(0,orientation.indexOf("xml")-1);
 
            var iconUrl = layoutObject.hero_icon_url;
            if(iconUrl && iconUrl.length > 2048 && isIE ){ // to solve rendered image loading in IE for long urls
 
                var start = iconUrl.indexOf("/MONTAGE_OUTPUT=");
                var end = iconUrl.indexOf("/",start+1);
                var wh = iconUrl.substring(start+"/MONTAGE_OUTPUT=".length,end); // ex : 158x102
                wh = wh.split("x");
                selfLoadUrl = getSelfLoadUrl(iconUrl);
                var iFrameHtml = "<iframe src='"+selfLoadUrl+"' width='"+wh[0]+"' height='"+wh[1]+"' frameborder='no'    border='1'    marginwidth='0'   marginheight='0'   scrolling='no'>";
                $("LayoutPreview").innerHTML = iFrameHtml ;
            }else{
                $("LayoutPreview").innerHTML= "<img src='"+layoutObject.hero_icon_url+"' title='"+layoutObject.templatename+"'></img>"
            }
            $("LargeLayoutPreviewImg").setAttribute("url",layoutObject.previewurl);// (rendered image);
            $(selectedLayoutSize+"_LargeViewCardText").hide();
            $(sku+"_LargeViewCardText").show();
            $("layoutName").innerHTML =  oCardsThemeLayoutDataComponent.themeDisplayName ? oCardsThemeLayoutDataComponent.themeDisplayName : cardsGlobal.selectedTheme;
            var photoCount = layoutObject.userphotos.length;            
            if(typeof isPhotoCountDisplaySupported != "undefined" && isPhotoCountDisplaySupported=="false"){
          	  photoCount = "";
            }else{
              photoCount = parseInt(photoCount) == 1 ? photoCount+" "+photoText : photoCount+" "+photosText;
            }
            $("layoutPhotoCount").innerHTML = photoCount ;
            $(selectedLayoutSize+"_Glossy_PriceText").hide();           $(selectedLayoutSize+"_Matte_PriceText").hide();
            if($(selectedLayoutSize+"_Stationary_PriceText")!= null)
                $(selectedLayoutSize+"_Stationary_PriceText").hide();
            $(sku+"_Glossy_PriceText").show();  $(sku+"_Matte_PriceText").show();
            if($(sku+"_Stationary_PriceText")!=null)
                $(sku+"_Stationary_PriceText").show();
        }
        cardsGlobal.selectedLayout = layoutId;
        selectedLayoutSize = sku;
        cardsGlobal.selectedOrientation = orientation;
}
 
initCaps = function(name){
        var themeArray = name.split('_');
        var theme = "";
        for(var index=0; index<themeArray.length; index++){
                var token = themeArray[index];
                theme = theme + token.charAt(0).toUpperCase() + token.substring(1);
                if(index != (themeArray.length)-1)
                        theme = theme + "_";
        }
        return theme;
}
 
initCapital = function(name){
    if(_websiteInfo.getRegion() == 'snapfish_eu' && _websiteInfo.getWebsiteName()!= 'snapfish_uk')
    return name.charAt(0).toUpperCase() + name.substring(1);
        else return name;
}

