/**
 * <br> $Header: /home/sclark/cvs2svn/cvsroot/website/scripts/siras.panels.storyviewer.js,v 1.4 2010-05-04 19:56:01 doconnor Exp $
 *
 * Author: J. Myron Smith
 *
 * <br> Copyright 1999-2010 by SiRAS.com.
 * <br> All rights reserved. "SIRAS' technology is protected by one or more of U.S. Patents."
 *
 * This is the 'Gallery of Retail Fraud' StoryViewer Panel compositing javascript code.
 */
siras.panels = {};

siras.storyViewerInitialize = function pageInitialize(){
  var pageVars = {}
  pageVars.config = {};

  pageVars.config.id = "storyViewerId";
  pageVars.config.width = 432;
  pageVars.config.borderWidth = 10;
  pageVars.config.imagePreviewWidth = 86;
  pageVars.config.effectsEnabled = true;
  pageVars.config.pageEnvTextDivHAdj = 4;
  pageVars.config.imageBaseUri = "../../images/";
  pageVars.config.storyData = {};
  pageVars.config.storyData.imageBaseUri = "../../GORFstories/images/";
  pageVars.config.storyData.storyArray = [
                                              { image: 'DigitalCamera_SIRAS.jpg',
                                                imageX: '4288',
                                                imageY: '2848',
                                                thumb: 'DigitalCamera_SIRAS_thumb.jpg',
                                                imageCaption: 'Film camera returned inside a digital camera box',
                                                heading: '"Trade-in Program"',
                                                text: 'This is an example of an all-too-familiar scenario where individuals, tired of their old item, ' +
                                                      'purchase a new one to replace it. They then "return" the old one in the new item\'s box and with ' +
                                                      'the new item\'s receipt - in effect getting the new one for free.'
                                              },
                                              { image: 'iPodForLegal.jpg',
                                                imageX: '4200',
                                                imageY: '1800',
                                                imageCaption:'Three digital media player boxes: one returned with a granite tile, the second with AAA ' +
                                                             'batteries and the third with a deck of playing cards',
                                                thumb: 'iPodForLegal_thumb.jpg',
                                                heading: '"Apples and Oranges"',
                                                text: 'These examples represent a national fraud epidemic of "brick-in-box" returns where similar cases are ' +
                                                      'reported by nearly every retailer and from every region of the country. With this return fraud, ' +
                                                      'customers bought digital media players and replaced them in the original box with something of ' +
                                                      'relatively similar size and weight. In these cases, the thieves carefully repackage the "brick" ' +
                                                      'in the original product carton, shrink-wrap it, then return it to the retailer as "new" for a full ' +
                                                      'refund.' +
                                                      '<br/><br/>The stolen units are commonly then sold through on-line auction sites to pawn shops or even ' +
                                                      'shipped overseas. Sometimes the "returns" look so convincing, they even end up back on store shelves ' +
                                                      'and are re-sold to unsuspecting customers. Imagine their surprise when get home and open their newly ' +
                                                      'purchased item.'
                                              },
                                              { image: 'NintendoDSlite_sardines_SIRAS.jpg',
                                                imageX: '4288',
                                                imageY: '2848',
                                                imageCaption: 'Nintendo DS&#153; box with sardine can',
                                                thumb: 'NintendoDSlite_sardines_SIRAS_thumb.jpg',
                                                heading: '"Something\'s Fishy"',
                                                text: 'Nintendo, like nearly every consumer electronics manufacturer, has seen an unusual variety of ' +
                                                      'brick-in-box return fraud. The sardine can returned in a handheld device box was one of the more ' +
                                                      'humorous ones.'
                                              },
                                              { image: 'PlasmaTV_Headstone_SIRAS.jpg',
                                                imageX: '4288',
                                                imageY: '2848',
                                                imageCaption: 'Tombstone returned in a plasma TV box',
                                                thumb: 'PlasmaTV_Headstone_SIRAS_thumb.jpg',
                                                heading: '"Kill Your Television?"',
                                                text: 'Who knew that a tombstone has similar shape and weight to a plasma television?'
                                              },
                                              { image: 'PinataPrinter_SIRAS.jpg',
                                                imageX: '3154',
                                                imageY: '2678',
                                                imageCaption: 'Pi&#241;ata returned in a printer box',
                                                thumb: 'PinataPrinter_SIRAS_thumb.jpg',
                                                heading: '"Fraud Fiesta!"',
                                                text: 'At first surprised to find a pi&#241;ata where they were expecting a printer return, the crew at this ' +
                                                      'manufacturer\'s return center found some satisfaction in discovering that the "brick" in this return ' +
                                                      'was a vessel full of candy to share.'
                                              },
                                              { image: "WiiPennies_SIRAS.jpg",
                                                imageX: "4288",
                                                imageY: "2848",
                                                imageCaption: 'Wii&#153; console from Nintendo returned with computer hard drive, pennies, batteries glue',
                                                thumb: "WiiPennies_SIRAS_thumb.jpg",
                                                heading: '"Retooled"',
                                                text: 'Illustrating unusual creativity and craftiness, this "retooled" Wii&#153; console weighs, ' +
                                                      '(to the ounce) the same as the product that was originally in the box. This was undoubtedly ' +
                                                      'a response to Internet blogs espousing that video game retailers and manufacturers were simply ' +
                                                      'weighing returns - not checking inside.'
                                              }
                                          ];

  pageVars.panel = new siras.panels.StoryViewer(pageVars.config);
}

siras.panels.StoryViewer = function() {
  var mCfg;
  var mImageViewer;
  var mTextViewer;
  var mImageScroller;
  var mId;
  var mIdViewerContainer;
  var mIdScroller;
  var mIdViewedStory;
  var mIdViewedStoryImage;

	var components = {
    ImageViewer: function(config) {
	    var cfg = config;

      function createImgHtml(index) {
        var viewAR = cfg.width / cfg.height;
        var imgW = mCfg.storyData.storyArray[index].imageX;
        var imgH = mCfg.storyData.storyArray[index].imageY;
        var imageAR = imgW / imgH;
        var renderedDim;
        var margin;
        var styleParams;

        if (imageAR < viewAR) { // limit by height of view
          renderedDim = imageAR * cfg.height;
          margin = parseInt((cfg.width - renderedDim)/ 2, 10);
          styleParams = ['height:', cfg.height, 'px; ', 'margin-left:', margin, 'px; '].join('');
        }
        else { // limit by width of view
          renderedDim = cfg.width / imageAR;
          margin = parseInt((cfg.height - renderedDim)/ 2, 10);
          styleParams = ['width:', cfg.width, 'px; ', 'margin-top:', margin, 'px; '].join('');
        }

        var renderData = [ '<img src="', mCfg.storyData.imageBaseUri, mCfg.storyData.storyArray[index].image,
                             '" style="', styleParams, '"/>',
                         ];
        return renderData.join('');
      }

	    function createHtml() {

	      var renderData = [
	                        '<div id="', cfg.id, '" style="background-color:#FFFFFF; width:', mViewedStoryWidth, 'px; height: 200px;"><div id="', cfg.id ,'Img">',
	                        createImgHtml(0),
	                        '</div></div>'
	                       ];
	      return renderData.join('');
	    }

	    function updateHtml(index) {
        var imgDivElem = document.getElementById(cfg.id+'Img');
        if (mCfg.effectsEnabled) {
          new Effect.Fade(imgDivElem, {duration:0.2, afterFinish:
            function() {
              imgDivElem.innerHTML = createImgHtml(index);
              Effect.Appear(imgDivElem, {duration:0.2});
            }
          });
        }
        else {
          imgDivElem.innerHTML = createImgHtml(index);
        }
	    }

	    return {
	      getHtml: function() {
          return createHtml(0, false);
	      },
	      updateImage: function(index) {
	        updateHtml(index);
	      }
	    }
	  },
	  TextViewer: function(config) {
	    var cfg = config;

      function createTxtHtml(index) {
        var renderData = [ '<div style="height:26px; color:#777; font-family:sans-serif; font-size:8pt; font-style:italic"><center><small>',
                           mCfg.storyData.storyArray[index].imageCaption,
                           '</center></small></div>',
                           '<div style="height: 1px; line-height:1px; padding:0 0 0 0; margin: 0 0 0 0; background-color:#AAA;">&nbsp;</div>',
                           '<div style="padding:3px 0px 0px 0px; margin: 0px 0px 0px 0px;"><big><b>', mCfg.storyData.storyArray[index].heading, '</b></big></div>',
                           '<div style="margin:0 0 0 0; padding:0 0 0 0; font-family:sans-serif; font-size:8pt; overflow-y:scroll; height:', cfg.height, 'px;">',
                           mCfg.storyData.storyArray[index].text,
                           '</div>'
                         ];
        return renderData.join('');
      }

	    function createHtml() {
	      var hAdj = cfg.pageEnvTextDivHAdj + (siras.env.getBrowser() === 'IE' ? 10 : 0);
        var renderData = ['<div id="', cfg.id, '" style="height:', cfg.height + 42 + hAdj, 'px; padding:6px; color:', cfg.color,
                          '; background-color:', cfg.backgroundColor, ';"><div id="', cfg.id ,'Txt">',
                          createTxtHtml(0),
                          '</div></div>'
                         ];
        return renderData.join('');
	    }

	    function updateHtml(index) {
	      var txtDivElem = document.getElementById(cfg.id + 'Txt');
	      if (mCfg.effectsEnabled) {
	        new Effect.Fade(txtDivElem, {duration:0.1, afterFinish:
	          function() {
	            txtDivElem.innerHTML = createTxtHtml(index);
              Effect.Appear(txtDivElem, {duration:0.1});
            }
	        });
	      }
	      else {
	        txtDivElem.innerHTML = createTxtHtml(index);
	      }
	    }


	    return {
	      getHtml: function() {
	        return createHtml();
	      },
	      updateText: function(index) {
	        updateHtml(index);
	      }
	    }
	  }
	}

	function updateViewedStory() {
	  var index = mImageScroller.getSelectedImageIndex();
	  mImageViewer.updateImage(index);
	  mTextViewer.updateText(index);
	}

  function getStoryContainerHtml() {
    var htmlArray = new Array(0);

    htmlArray.push(mImageViewer.getHtml());
    htmlArray.push(mTextViewer.getHtml());
    return htmlArray.join('');
  }

  function updateStoryContainerHtml() {
    var storyContainerElem = document.getElementById(mIdViewerContainer);
    storyContainerElem.innerHTML = getStoryContainerHtml();
  }

  function createPanel(cfg) {
    mCfg = cfg;
    mId = mCfg.id;
    mIdViewerContainer = mId + '_main';
    mIdViewedContainer = mId + '_viewedStory';
    mIdScroller = mId + '_imageScroller';
    mIdViewedStoryImage = mIdViewedContainer + 'Image';
    mIdViewedStoryHeading = mIdViewedContainer + 'Heading';
    mIdViewedStoryText = mIdViewedContainer + 'Text';
    mViewedStoryWidth = mCfg.width - 2*mCfg.borderWidth;

    mCfg.TLcorner = "border_TLcorner.png";
    mCfg.TRcorner = "border_TRcorner.png";
    mCfg.BLcorner = "border_BLcorner.png";
    mCfg.BRcorner = "border_BRcorner.png";

    if (mCfg.imagePreviewWidth == null) {
      mCfg.imagePreviewWidth = 103;
    }

    mIsEnabled = (mCfg.isEnabled != null) ? mCfg.isEnabled : true;
    mCfg.storyData = mCfg.storyData || null;

    var html = new Array(0);
    var hasImage = (mCfg.storyData != null && mCfg.storyData.storyArray != null && mCfg.storyData.storyArray.length > 0 )? true : false;

    mImageViewer = new components.ImageViewer({id:mCfg.id + "ImageViewer",
                                               width: mViewedStoryWidth,
                                               height: 200});
    mTextViewer = new components.TextViewer({id: mCfg.id + "TextViewer",
                                             height: 100,
                                             pageEnvTextDivHAdj: mCfg.pageEnvTextDivHAdj,
                                             color: "#003366",
                                             backgroundColor: "#FFFFFF"});

    //padding:', mCfg.borderWidth, 'px; border:1px solid black;
    html.push('<table cellpadding="0px" cellspacing="0px" frame="void" rules="none"><tbody>');
    html.push('<tr><td style="background-image:url(', mCfg.imageBaseUri, mCfg.TLcorner,')"></td><td style="height:11px; background-color:#002C63;"></td><td style="background-image:url(', mCfg.imageBaseUri, mCfg.TRcorner,')"></td></tr>');
    html.push('<tr><td style="width:11px; background-color:#002C63;"></td><td><div id="', mIdViewerContainer, '" style="background-color:#002C63; width:', mViewedStoryWidth, 'px;">');
    html.push('<div style="font-family:sans-serif; background-color:white: border:1px solid black; width:', mViewedStoryWidth,'px;">');
    html.push(getStoryContainerHtml());
    html.push('</div>');

    var imageScrollerItem = siras.widgets.ImageScroller;
    var imageScrollerClass = Class.create(new imageScrollerItem);

    var isEnabled = mCfg.storyData.storyArray.length > 1;
    var filmColor = '#00AAEF'; // '#844931'
    var boxWFF = mCfg.imagePreviewWidth;
    var boxWIE = boxWFF;// - 3;
    var scrollerConfig = {
      id: mIdScroller,
      enabled: isEnabled,
      effectsEnabled: mCfg.effectsEnabled,
      marginTop: 5,
      marginRight: 0,
      marginLeft: 0,
      marginBottom: 0,
      width: mCfg.width - 2*mCfg.borderWidth,
      //height: 80,
      imageBoxWidth: siras.env.getBrowser() === 'IE' ? boxWIE : boxWFF,
      //imageBoxSpacing: 20,
      imageBorderWidth : 2,
      selectedBorderWidth : 2,
      imageBorderColor : filmColor,
      selectedBorderColor : '#FFAA00', //'#401901',
      scrollRgnBgColor: filmColor,
      scrollRgnBorderWidth: 0, //5,
      scrollRgnBorderStyle:'none', //filmsides',
      scrollRgnBorderColor:'#FFFFFF',
      backgroundColor:'#B5E7FF',
      borderColor:'#B5E7FF',
      borderWidth: 3,
      onClickHandler: updateViewedStory,
      btnImageUri: mCfg.imageBaseUri,
      imageBaseUri: mCfg.storyData.imageBaseUri,
      imageArray: mCfg.storyData.storyArray,
      useDefaultBtnImages: true
    }
    mImageScroller = new imageScrollerClass(scrollerConfig);
    html.push(mImageScroller.getHtml());
    html.push('</div></td><td style="width:11px; background-color:#002C63;"></td></tr>')
    html.push('<tr><td style="background-image:url(', mCfg.imageBaseUri, mCfg.BLcorner,')"></td><td style="height:11px; background-color:#002C63;"></td><td style="background-image:url(', mCfg.imageBaseUri, mCfg.BRcorner,')"></td></tr>');
    html.push('</tbody></table>');

    var panel = document.getElementById(mId);
    panel.innerHTML = html.join('');

    mImageScroller.finishInit();
    mInitialized = true;
  }

	return function(config) {
		if (config.id == null) {
			alert('error - required parameter: id missing' );
			return;
		}

		createPanel(config);

		return {
			getVersion: function() {
				return version;
			},
			getHtml: function() {
				return mHtml;
			},
			setEnabled: function(enable) {
				mCfg.enabled = enable;
				update();
			}
		}
	}
}();
