Effect.BlindRight = function(element) {
  element = $(element);
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({
    scaleContent: false,
    scaleY: false,
    scaleFrom: 0,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makeClipping().setStyle({
        width: '0px',
        height: effect.dims[0] + 'px'
      }).show();
    },
    afterFinishInternal: function(effect) {
      effect.element.undoClipping();
    }
  }, arguments[1] || { }));
};

Effect.BlindLeft = function(element) {
  element = $(element);
  element.makeClipping();
  return new Effect.Scale(element, 0,
    Object.extend({ scaleContent: false,
      scaleY: false,
      restoreAfterFinish: true,
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping();
      }
    }, arguments[1] || { })
  );
};

var base = Class.create({
  initialize: function(params) {
    params = (params) ? params:{};
    this.container = new Element('div');
    
    this.init(params);
  },
  
  getDomObj: function() {
    if (!this.container.firstDescendant()) {
      this.buildDomObj();
    }
    return this.container;
  }
});

var baseWidget = Class.create(base, {
  initialize: function(params) {
    this.imgPath = "/components/com_sngevents/views/event/tmpl/images/";
    this.spanBtn = new Element('span', {"class":"widgetButtonContainer"});
    this.button = new Element('img', {"class":"widgetButton", "src":this.imgPath + params.btnSrc});
    this.canvas = new Element('div', {"class":"widgetCanvas"});
    this.animated = false;
    
    this.parent = params.parent;
    this.heritage = Object.clone(this.parent.heritage);
    this.controlContainer = params.parent;
    
    this.spanBtn.appendChild(this.button);
    
    this.addBaseObservers();
    this.init(params);
  },
  
  addBaseObservers: function() {
    this.spanBtn.observer = this.show.bindAsEventListener(this);
    this.spanBtn.observe('click', this.spanBtn.observer);
  },
  
  fadeIn: function() { this.show() },
  
  fadeOut: function() { this.hide() },
  
  hide: function() {
    if ((this.canvas.visible()) && (!this.animated)) {
      this.animated = true;
      this.spanBtn.removeClassName("widgetButtonActive");
      new Effect.Fade(this.canvas, { "duration":.3, afterFinish: function() { this.animated = false; }.bind(this) });
    }
  },
  
  show: function() {
    if (!this.canvas.visible()) {
      this.animated = true;
      this.parent.hideWidgets();
      this.spanBtn.addClassName("widgetButtonActive");
      new Effect.Appear(this.canvas, { "duration":.3, afterFinish: function() { this.animated = false; }.bind(this) });
    }
  }
});

var buyPanel = Class.create({
  initialize: function(params) {
    var titleText = null;
  
    this.parent = (params.parent) ? params.parent:null;
    this.container = new Element('div', {'id':'buyPanel'});
    this.imgExpandTab = new Element('img');
    this.header = new Element('div');
    this.headerText = new Element('span', {'id':'buyPanelHeader'}).update(JText['BUY_THIS_PHOTO']||'Buy This Photo');
    
    
    this.form = new Element('form');
    
    this.contSizeSelector = new Element('div', {'class':'buyImgRow'});
    this.spanSizeSelector = new Element('span', {'class':'formLabel'}).update(JText['SELECT_SIZE'] || 'Select Size');
    this.selectSizeSelector = new Element('select', {'id':'sizeSelector', 'name':'sizeSelector'});
    
    
    this.contBorderSelector = new Element('div', {'class':'buyImgRow'});
    titleText = JText['BORDER_DETAIL'] || 'Your print can include a white border around the image.';
    this.contBorderSelector.writeAttribute('title', titleText);
    this.spanBorderSelector = new Element('span', {'class':'formLabel'}).update(JText['BORDER'] || 'Border:');
    this.cbBorderSelector = new Element('input', {'type':'checkbox', 'id':'cbBorderSelector', 'name':'cbBorderSelector', 'value':'1'});
    
    this.contMatteGlossSelector = new Element('div', {'class':'buyImgRow'});
    titleText = JText['MATTE_GLOSS'] || 'When printing digital photos you have a choice between matte and glossy photo prints.';
    this.contMatteGlossSelector.writeAttribute('title', titleText);
    this.spanMatteGlossSelector = new Element('span', {'class':'formLabel'}).update(JText['IMAGE_FINISH'] || 'Image Finish:');
    this.labelMatte = new Element('label');
    this.radioMatte = new Element('input', {'type':'radio', 'name':'mattegloss', 'value':'matte'});
    this.spanMatte = new Element('span').update(JText['MATTE'] || 'Matte');
    this.labelGloss = new Element('label');
    this.radioGloss = new Element('input', {'type':'radio', 'name':'mattegloss', 'value':'glossy', 'checked':'true'});
    this.spanGloss = new Element('span').update(JText['GLOSSY'] || 'Glossy');
    
    this.contQty = new Element('div', {'class':'buyImgRow'});
    this.spanQty = new Element('span', {'class':'formLabel'}).update(JText['QUANTITY'] || 'Quantity');
    this.numQty = new Element('input', {'type':'text', 'size':'2', 'maxlength':'2'});
    
    this.cart = new cartBox({parent:this});
    
    this.contAddCart = new Element('div', {'class':'buyImgRow'});
    var btnAddCartVal = JText['ADD_TO_CART']||'Add To Cart';
    this.btnAddCart = new Element('input', {'type':'button','value':btnAddCartVal});
    
    this.contJumpCart = new Element('div', {"class":"buyImgRow"});
    var btnJumpToCartVal = JText['VIEW_CART']||'View Cart';
    this.btnJumpCart = new Element('input', {"type":"button", "value":btnJumpToCartVal});
    
    var btnContinueShoppingVal = JText['CONTINUE_SHOPPING']||'Continue Shopping';
    this.btnContinueShopping = new Element('input', {"type":"button", "value":btnContinueShoppingVal});
    this.btnContinueShopping.setStyle({"float":"left"});
    
    this.arRateCardItemIds = new Array();
    this.overlay = new elOverlay({contEl:this.parent.contBuyPanel, el:this.parent.contBuyPanel});
  },
  
  addSizeOptions: function() {
    this.selectSizeSelector.options.length = 0;
    var objThis = this;
    
    new Ajax.Request('/', {
      method: 'post',
      parameters: {
        option: 'com_sngevents',
        controller: 'cart',
        task: 'get_option_list'
      },
      onSuccess: function(transport) {
        var objResponse = transport.responseText.evalJSON(true);
        if (objResponse.arErr.length) {
          var errList = "";
          objResponse.arErr.each(function(s) {
            errList += s + "\n";
          });
          alert(errList);
          objThis.hidePanel();
        } else {
          var optText = "";
          objResponse.dataResult.each(function(s) {
            optText = s.optionText + ' (' + s.cost + ')';
            objThis.selectSizeSelector.options[objThis.selectSizeSelector.options.length] = new Option(optText, s.rateCardItemDetailId);
            objThis.arRateCardItemIds[s.rateCardItemDetailId] = s.rateCardItemId;
          });
          objThis.selectSizeSelector.selectedIndex = -1;
        }
      }
    });
    
  },
  
  buildDomObj: function() {
    this.header.appendChild(this.headerText);
    this.container.appendChild(this.header);
    
    this.contSizeSelector.appendChild(this.spanSizeSelector);
    this.contSizeSelector.appendChild(this.selectSizeSelector);
    
    this.contBorderSelector.appendChild(this.spanBorderSelector);
    this.contBorderSelector.appendChild(this.cbBorderSelector);
    
    this.contMatteGlossSelector.appendChild(this.spanMatteGlossSelector);
    this.labelMatte.appendChild(this.radioMatte);
    this.labelMatte.appendChild(this.spanMatte);
    this.labelGloss.appendChild(this.radioGloss);
    this.labelGloss.appendChild(this.spanGloss);
    this.contMatteGlossSelector.appendChild(this.labelMatte);
    this.contMatteGlossSelector.appendChild(this.labelGloss);
    
    this.contQty.appendChild(this.spanQty);
    this.contQty.appendChild(this.numQty);
    
    this.contAddCart.appendChild(this.btnAddCart);
    this.contAddCart.appendChild(new Element('div', {'class':'clear'}));
    
    this.contJumpCart.appendChild(this.btnJumpCart);
    this.contJumpCart.appendChild(this.btnContinueShopping);
    this.contJumpCart.appendChild(new Element('div', {'class':'clear'}));
    
    
    this.form.appendChild(this.contSizeSelector);
    this.form.appendChild(this.contBorderSelector);
    this.form.appendChild(this.contMatteGlossSelector);
    this.form.appendChild(this.contQty);
    this.form.appendChild(this.contAddCart);
    this.form.appendChild(this.cart.getDomObj());
    this.form.appendChild(this.contJumpCart);
    
    this.container.appendChild(this.form);
    
    this.container.hide();
    this.addObservers();
    this.addSizeOptions();
  },
  
  cartInfo: function() {
    this.cart.contOrders.purge();
    for (var i=0; i<this.parent.objImg.arOrdItems.length; i++) {
      this.cart.contOrders.appendChild(this.parent.objImg.arOrdItems[i].getDomObj());
    }
  },
  
  closeParent: function() {
    this.parent.fade();
  },
  
  getDomObj: function() {
    if (!this.container.firstDescendant()) {
      this.buildDomObj();
      
    }
    return this.container;
  },
  
  addObservers: function() {
    var objThis = this;
    this.form.observe('submit', function(e){Event.stop(e);});
        
    this.selectSizeSelector.observer = this.hiRezCheck.bindAsEventListener(this);
    this.selectSizeSelector.observe('change', this.selectSizeSelector.observer);
    
    this.btnAddCart.observer = this.addToCart.bindAsEventListener(this);
    this.btnAddCart.observe('click', this.btnAddCart.observer);
    
    this.btnJumpCart.observer = function() { location.href = "/?option=com_sngcart"; };
    this.btnJumpCart.observe('click', this.btnJumpCart.observer);
    
    this.btnContinueShopping.observer = this.closeParent.bindAsEventListener(this);
    this.btnContinueShopping.observe('click', this.btnContinueShopping.observer);
  },
  
  hiRezCheck: function() {
    if (this.selectSizeSelector.selectedIndex > -1) {
      var photoSelectedValue = this.selectSizeSelector.options[this.selectSizeSelector.selectedIndex].value;
      var rateCardItemId = this.arRateCardItemIds[photoSelectedValue];
    }
    if ((this.selectSizeSelector.selectedIndex == -1) || (rateCardItemId == 48)) {
      this.cbBorderSelector.disabled = true;
      this.cbBorderSelector.checked = false;
      this.contBorderSelector.setStyle({'color':'#C0C0C0'});
      this.radioMatte.checked = false;
      this.radioMatte.disabled = true;
      this.radioGloss.checked = false;
      this.radioGloss.disabled = true;
      this.contMatteGlossSelector.setStyle({'color':'#C0C0C0'});
      this.numQty.value = (this.selectSizeSelector.selectedIndex == -1) ? '':1;
      this.numQty.disabled = true;
      this.contQty.setStyle({'color':'#C0C0C0'});
      this.numQty.setStyle({backgroundColor: '#E9E9E9', borderColor: '#EF757E'});
    } else {
      this.cbBorderSelector.disabled = false;
      this.contBorderSelector.setStyle({'color':'black'});
      this.radioMatte.disabled = false;
      this.radioGloss.disabled = false;
      this.radioGloss.checked = true;
      this.contMatteGlossSelector.setStyle({'color':'black'});
      this.numQty.disabled = false;
      if (!this.numQty.value) { this.numQty.value = 1; }
      this.contQty.setStyle({'color':'black'});
      this.numQty.setStyle({backgroundColor: '#DBDBDB', borderColor: '#AF151E'});
    }
  },
  
  resetForm: function() {
    this.form.reset();
    this.selectSizeSelector.selectedIndex = -1;
    this.radioGloss.checked = true;
    this.hiRezCheck();
  },
  
  formValid: function() {
    var errMsg = '';
    if (this.selectSizeSelector.selectedIndex > -1) {
      var photoSelectedValue = this.selectSizeSelector.options[this.selectSizeSelector.selectedIndex].value;
      var rateCardItemId = this.arRateCardItemIds[photoSelectedValue];
    }
    if (this.selectSizeSelector.selectedIndex == -1) {
      errMsg += "Select a size.\n";
    } else if (rateCardItemId != 48) {
      if ((!this.radioMatte.checked) && (!this.radioGloss.checked)) {
        errMsg += "Select a finish.\n";
      }
      if (isNaN(Number(this.numQty.value)) || (Number(this.numQty.value) == 0)) {
        errMsg += "Enter a quantity.\n";
      }
    }
    if (errMsg) { alert(errMsg); }
    if (errMsg) { return false; } else { return true; }
  },
  
  showPanel: function() {
    new Effect.BlindRight(this.container);
  },
  
  hidePanel: function() {
    new Effect.BlindLeft(this.container);
  },
  
  addToCart: function() {
    if (this.formValid()) {
      var params = {};
      if (this.selectSizeSelector.selectedIndex > -1) {
        var photoSelectedValue = this.selectSizeSelector.options[this.selectSizeSelector.selectedIndex].value;
        var rateCardItemId = this.arRateCardItemIds[photoSelectedValue];
      }
      params.sizeText = (this.selectSizeSelector.selectedIndex > -1) ? this.selectSizeSelector[this.selectSizeSelector.selectedIndex].text:null;
      params.rateCardItemId = rateCardItemId;
      params.rateCardItemDetailId = $F(this.selectSizeSelector);
      params.border = $F(this.cbBorderSelector);
      params.finish = null;
      if (this.radioMatte.checked) {
        params.finish = this.radioMatte.value;
      }
      if (this.radioGloss.checked) {
        params.finish = this.radioGloss.value;
      }
      params.qty = $F(this.numQty);
      params.photoId = this.parent.objImg.id;
      
      this.cart.addToCart(params);
      this.resetForm();
    }
  }
});

var emailPopup = Class.create(base, {
  init: function(params) {
    this.container.writeAttribute({"id":"emailDlg"});
    this.emailForm = new Element('form');
    this.toField = new Element('form');
  },
  
  addObservers: function() {
    this.emailForm.submitObserver = this.stopSubmit.bindAsEventListener(this);
    this.emailForm.observe('submit', this.emailForm.submitObserver);
  },
  
  stopSubmit: function(e) {
    Event.stop(e);
  }
});

var eventImg = Class.create(base, {
  initialize: function(params) {
    this.heritage = {"eventImg":this}
    this.container = params.container;
    this.contImgSmall = this.container.select('div.innerImg')[0];
    this.imgSmall = this.contImgSmall.select('img')[0];
    this.caption = params.imgData.cap;
    this.id = params.imgData.id;
    this.idx = params.imgData.idx;
    this.archived = (params.imgData.archive_status_id > 1) ? true:false;
    this.sell = params.imgData.sell;
    this.fbLink = "http://snapd.at/" + params.imgData.short_url_fb;
    this.twLink = "http://snapd.at/" + params.imgData.short_url_tw;
    this.emLink = "http://snapd.at/" + params.imgData.short_url_em;
    //this.emailLink = "http://snapd.at/e" + params.imgData.short_url_tw.substring(1);
    
    this.optionsPanel = new optionsPanel(params.imgData, this);
    this.objectName = "eventImg";
    this.buildDomObj();
    this.addObservers();
  },
  
  addObservers: function() {
    this.contImgSmall.observer = this.imgClick.bindAsEventListener(this);
    this.contImgSmall.observe('click', this.contImgSmall.observer);
    //this.contImgSmall.observe('click', inBoxStop);
  },
  
  buildDomObj: function() {
    if ((Prototype.Browser.IE7) || (Prototype.Browser.IE6)) {
      
      var domParent = this.container.getOffsetParent();
      var domParentOff = domParent.cumulativeOffset();
      var posOff = this.container.cumulativeOffset();
      
      var top = posOff.top - domParentOff.top + 160;
      top += (this.idx == 0) ? $('header').getHeight():0;
      var left = posOff.left - domParentOff.left - 15;
      this.optionsPanel.container.setStyle({"position":"absolute", "top": top + "px", "left": left + "px", "zIndex":80});
      if (this.idx == 0) {
        $('contentBtm').appendChild(this.optionsPanel.getDomObj());
      } else {
        $('imgCanvas').appendChild(this.optionsPanel.getDomObj());
      }
    } else {
      this.container.appendChild(this.optionsPanel.getDomObj());
    }
  },
  
  imgClick: function(e) {
    var evtEl = Event.element(e);
    //console.log(evtEl.tagName);
    if ((evtEl.tagName != 'INPUT') && (evtEl.tagName != "TEXTAREA")) { Event.stop(e); }
    this.optionsPanel.fadeIn();
  }
});

var captionPanel = Class.create(base, {
  init: function(params) {
    this.container.writeAttribute({"class":"captionPanel"});
    this.imageContainer = params.parent;
    this.parent = params.parent;
    this.captionText = params.imgData.cap;
    this.contCaption = new Element('div', {"class":"captionContainer"});
    this.spanCaption = new Element('span');
    this.dotdotdot = new Element('div', {"class":"dotdotdot"});
    this.btnClose = new Element('img', {"class":"capPanClose", "src":"/components/com_sngevents/views/event/tmpl/images/btn_close.png"});
    this.height = null;
    this.animated = false;
    
    if (Prototype.Browser.IE6 || Prototype.Browser.IE7) {
      this.container.setStyle({"backgroundColor":"black"});
    }
    if (Prototype.Browser.IE8) {
      this.container.setStyle({"filter":"alpha(opacity=80)"});
    }
    
    this.addObservers();
  },
  
  addObservers: function() {
    this.btnClose.observer = this.toggleView.bindAsEventListener(this);
    this.dotdotdot.observer = this.toggleView.bindAsEventListener(this);
    
    this.btnClose.observe("click", this.btnClose.observer);
    this.dotdotdot.observe("click", this.dotdotdot.observer); 
  },
  
  buildDomObj: function() {
    this.spanCaption.update(this.captionText);
    this.dotdotdot.update('...');
    
    this.contCaption.appendChild(this.btnClose);
    this.contCaption.appendChild(this.spanCaption);
    
    this.container.appendChild(this.contCaption);
    this.container.appendChild(this.dotdotdot);
    
    this.dotdotdot.hide();
  },
  
  setDims: function() {
    this.width = this.parent.width - 28;
    this.captionHeight = this.contCaption.getHeight();
    this.container.setStyle({"width":this.width + "px", "top":"auto", "bottom":"7px"});
    
  },
  
  toggleView: function() {
    if (!this.height) {
      this.height = this.contCaption.getHeight();
      this.container.setStyle({"height":this.height + "px"});
    }
    if (!this.animated) {
      var objThis = this;
      this.animated = true;
      if (this.contCaption.visible()) {
        this.contCaption.hide();
        var toLeft = Math.floor(this.imageContainer.width / 2 - 21);
        new Effect.Morph(this.container, {
          "style": "left:" + this.toLeft + "px; height: 12px; width: 36px;",
          "duration": .4,
          "afterFinish": function() {
            objThis.animated = false;
            objThis.dotdotdot.show();
          }
        });
      } else {
        this.dotdotdot.hide();
        new Effect.Morph(this.container, {
          "style": "left:18px; height:" + this.height + "px; width:" + this.width + "px;",
          "duration": .4,
          "afterFinish": function() {
            objThis.animated = false;
            objThis.contCaption.show();
          }
        });
      }
    }
  }
  
});

var optionsPanel = Class.create(base, {
  initialize: function(imgData, parent) {
    this.parent = parent;
    this.eventImg = parent;
    this.objectName = "optionsPanel";
    this.animated = false;
    this.heritage = Object.clone(this.parent.heritage);
    this.heritage.optionsPanel = this;
    this.intervalCartCount = null;
    
    this.container = new Element('div', {"class":"contOptionsPanel"});
    this.contImage = new imageContainer(imgData, this);
    this.controlCanvas = new controlContainer({"imgData":imgData, "parent":this});
    
    this.addObservers();
    this.buildDomObj();
  },
  
  addObservers: function() {
    //this.container.observer = function(e){ Event.stop(e); };
    this.container.observe('click', inBoxStop);
  },
  
  buildDomObj: function() {
    this.container.hide();
    
    this.container.appendChild(this.contImage.getDomObj());
    this.container.appendChild(this.controlCanvas.getDomObj());
  },
  
  hide: function() { this.fadeOut() },
  
  show: function() { this.fadeIn() },
  
  fadeIn: function() {
    if (!this.container.visible()) {
      this.animated = true;
      this.hideAll();
      var objThis = this;
      new Effect.Appear(this.container, {
        duration: .3,
        afterFinish: function() {
          objThis.animated = false;
          objThis.controlCanvas.arWidgets[0].show();
          if ((objThis.container.viewportOffset().top < 20) || (objThis.container.viewportOffset().top > document.viewport.getHeight() + 100)) {
            smoothScroll(objThis.contImage.container.cumulativeOffset().top);
          }
        }
      });
      this.contImage.load();
      if (typeof objThis.controlCanvas.buy != "undefined") {
        this.controlCanvas.buy.cart.getCartContent();
        var boundUpdater = this.controlCanvas.buy.updateCartInfo.bind(this.controlCanvas.buy);
        this.intervalCartCount = setInterval(boundUpdater, 1000);
      }
      if ((typeof objThis.controlCanvas.comments != "undefined") && (!this.controlCanvas.comments.comments.loaded)) {
        this.controlCanvas.comments.comments.getComments();
      }
      //setTimeout(function() {  }, 
    }
  },
  
  fadeOut: function(wait) {
    /*******************************************************************************************************
    * Fade out the options panel                                                                           *
    *   if true is passed and an animation is in progress the function will wait 1/10th of a second before *
    *   attemting to fade again.                                                                           *
    *******************************************************************************************************/
    if ((this.container.visible()) && (!this.animated)) {
      this.animated = true;
      var objThis = this;
      new Effect.Fade(this.container, {duration: .3, afterFinish: function() { objThis.animated = false; }});
      if (typeof objThis.controlCanvas.buy != "undefined") {
        clearInterval(this.intervalCartCount);
      }
    } else {
      if ((this.animated) && (wait)) {
        var objThis = this;
        setTimeout(function() { objThis.fadeOut(wait); }, 100);
      }
    }
  },
  
  hideAll: function() {
    /*****************************************
    * Hide all optionsPanels except this one *
    *****************************************/
    var objThis = this;
    arObjImg.each(function(s) {
      if (objThis.parent != s) {
        s.optionsPanel.fadeOut(true);
      }
    });
  }
  
});

var controlContainer = Class.create(base, {
  init: function(params) {
    this.container.writeAttribute({"class":"innerOptionsPanel"});
    this.headerBar = new Element('div', {"class":"optionsHeaderBar"});
    this.spanButtons = new Element('span', {"class":"widgetContainer"});
    this.widgetStage = new Element('div', {"class":"widgetStage"});
    this.parent = params.parent;
    this.optionsPanel = params.parent;
    this.heritage = Object.clone(this.parent.heritage);
    this.heritage.controlContainer = this;
    this.arWidgets = new Array();
    
    
    if ((!this.heritage.eventImg.archived) && (this.heritage.eventImg.sell) && (regionCode == 1)) {
      this.buy = new widgetBuyPhoto({"parent":this, "btnSrc":"icon_shoppingcart.png", "imgId":params.imgData.id});
      this.arWidgets.push(this.buy);
    }
    
    this.comments = new widgetComment({"parent":this, "btnSrc":"icon_comments.png", "imgId":params.imgData.id});
    this.arWidgets.push(this.comments);
    
    this.share = new widgetShare({"parent":this, "btnSrc":"icon_share.png", "imgId":params.imgData.id});
    this.arWidgets.push(this.share);
    
  },
  
  buildDomObj: function() {
    if (typeof this.buy != "undefined") {
      this.spanButtons.appendChild(this.buy.spanBtn);
      this.widgetStage.appendChild(this.buy.canvas);  
    }
    
    this.spanButtons.appendChild(this.comments.spanBtn);
    this.spanButtons.appendChild(this.share.spanBtn);
    
    this.widgetStage.appendChild(this.comments.canvas);
    this.widgetStage.appendChild(this.share.canvas);
    
    this.headerBar.appendChild(this.spanButtons);
    this.container.appendChild(this.headerBar);
    this.container.appendChild(this.widgetStage);
  },
  
  hideWidgets: function() {
    this.arWidgets.each(function(s) {
      s.hide();
    });
  }
  
});

var imageContainer = Class.create(base, {
  initialize: function(params, parent) {
    params = (params) ? params:{};
    this.container = new Element('div', {"class":"contLargeImage"});
    this.constrainer = new Element('div', {"class":"imgConstrainer"});
    this.bigImg = new Element('img');
    this.preloader = new Element('img', {"src":"/components/com_sngevents/views/event/tmpl/images/loading.gif", "class":"preloader"});
    this.optionsPanel = parent;
    this.parent = parent;
    this.captionText = params.cap;
    this.btnClose = new closeButton({"optionsPanel":this.optionsPanel});
    if (params.cap) {
      this.caption = new captionPanel({"parent":this, "imgData":params});
    }
    this.controlOverlay = null;
    this.idx = params.idx;
    
    //this.container.writeAttribute({"class":"contLargeImage"});
    this.bigImgUrl = params.lg;
    this.bigImgLoaded = false;
    this.height = 0;
    this.width = 0;
    this.addObservers();
  },
  
  addObservers: function() {
    this.bigImg.loadObserver = this.imgLoaded.bindAsEventListener(this);
    this.bigImg.observe("load", this.bigImg.loadObserver);
  },
  
  buildDomObj: function() {
    this.container.appendChild(this.constrainer);
    this.constrainer.appendChild(this.bigImg);
    this.constrainer.hide();
    this.setContImgSize();
    this.controlOverlay = new imgIndexController({"idx":this.idx, "parent":this});
    this.container.appendChild(this.controlOverlay.getDomObj());
    this.controlOverlay.container.setStyle({"zIndex":2});
    this.container.appendChild(this.btnClose.getDomObj());
    this.container.appendChild(this.preloader);
    
    if (typeof this.caption != "undefined") {
      this.container.appendChild(this.caption.getDomObj());
      this.caption.container.setStyle({"zIndex":4})
    }
    this.btnClose.container.setStyle({"zIndex":3});
  },
  
  imgLoaded: function() {
    if (!this.bigImgLoaded) {
      //this.bigImg.hide();
      //this.constrainer.appendChild(this.bigImg);
      //this.container.appendChild(this.constrainer);
      //this.constrainer.show();
      new Effect.Appear(this.constrainer, {
        "duration":.3,
        afterFinish: function() { 
          this.constrainer.setStyle({"zIndex":1});
          this.controlOverlay.container.setStyle({"zIndex":2});
        }.bind(this)
      });
      new Effect.Fade(this.preloader, {"duration":.3});
      this.bigImgLoaded = true;
    }
  },
  
  load: function() {
    if (!this.bigImgLoaded) {
      this.positionPreloader();
      this.bigImg.writeAttribute({"src":this.bigImgUrl});
    }
  },
  
  setContImgSize: function() {
    var dims = this.optionsPanel.parent.imgSmall.getDimensions();
    if (dims.width > dims.height) {
      this.width = 400;
      this.height = Math.floor(dims.height * 400 / dims.width);
    } else {
      this.height = 400;
      this.width = Math.floor(dims.width * 400 / dims.height);
    }
    var top = (this.height + 15) * -1;
    this.container.setStyle({"height":this.height + "px", "width":this.width + "px", "top":top + "px"});
    this.constrainer.setStyle({"height":this.height + "px", "width":this.width + "px"});
    if (typeof this.caption != "undefined") { this.caption.setDims(); }
  },
  
  positionPreloader: function() {
    var left = Math.floor(this.width / 2 - 32) + "px";
    var top = Math.floor(this.height / 2 - 32) + "px";
    this.preloader.setStyle({"top":top, "left":left});
  }
});

var closeButton = Class.create(base, {
  init: function(params) {
    this.container.writeAttribute({"class":"optionsPanelBtnClose"});
    if (Prototype.Browser.IE6 || Prototype.Browser.IE7) {
      this.container.setStyle({"width":"66px", "backgroundColor":"black"});
    }
    if (Prototype.Browser.IE8) {
      this.container.setStyle({"filter":"alpha(opacity=80)"});
    }
    this.imgX = new Element('img', {"src":"/components/com_sngevents/views/event/tmpl/images/btn_close.png"});
    this.spanClose = new Element('span').update('CLOSE');
    this.optionsPanel = params.optionsPanel;
    
    this.mOverAnim = false;
    this.mOutAnim = false;
    
    this.addObservers();
  },
  
  addObservers: function() {
    if (!Prototype.Browser.IE6 && !Prototype.Browser.IE7) {
      this.container.moverObserver = this.mOver.bindAsEventListener(this);
      this.container.moutObserver = this.mOut.bindAsEventListener(this);
      this.container.observe('mouseover', this.container.moverObserver);
      this.container.observe('mouseout', this.container.moutObserver);
    }
    this.container.observer = this.closeClick.bindAsEventListener(this);
    
    this.container.observe('click', this.container.observer);
    
  },
  
  buildDomObj: function() {
    this.container.appendChild(this.imgX);
    this.container.appendChild(this.spanClose);
    if (!Prototype.Browser.IE6 && !Prototype.Browser.IE7) {
      this.spanClose.hide();
    }
  },
  
  closeClick: function(e) {
    Event.stop(e);
    this.optionsPanel.fadeOut();
  },
  
  mOut: function() {
    this.spanClose.hide();
  },
  
  mOver: function() {
    this.spanClose.show();
  }
});

var imgIndexController = Class.create(base, {
  init: function(params) {
    this.container.writeAttribute({"class":"bigImgOverlay"});
    this.panelPrev = new Element('div', {"class":"contPrev"});
    this.panelNext = new Element('div', {"class":"contNext"});
    this.btnNext = new Element('div', {"class":"IPNRight"}).update(JText['NEXT']);
    this.transpixelNext = new Element('img', {"src":"/components/com_sngevents/views/event/tmpl/images/transpixel.png"});
    this.transpixelPrev = new Element('img', {"src":"/components/com_sngevents/views/event/tmpl/images/transpixel.png"});
    this.btnNext.hide();
    this.btnPrev = new Element('div', {"class":"IPNLeft"}).update(JText['PREVIOUS']);
    this.btnPrev.hide();
    this.imageContainer = params.parent;
    this.optionsPanel = this.imageContainer.parent;
    this.eventImg = this.optionsPanel.parent;
    this.objectName = "imgIndexController";
    if (Prototype.Browser.IE8) {
      this.btnNext.setStyle({"filter":"alpha(opacity=80)"});
      this.btnPrev.setStyle({"filter":"alpha(opacity=80)"});
    }
    
  },
  
  addObservers: function() {
    this.panelPrev.mMoveObserver = this.showPrev.bindAsEventListener(this);
    this.panelPrev.mOutObserver = this.hidePrev.bindAsEventListener(this);
    this.panelPrev.observer = this.movePrev.bindAsEventListener(this);
    this.panelNext.mMoveObserver = this.showNext.bindAsEventListener(this);
    this.panelNext.mOutObserver = this.hideNext.bindAsEventListener(this);
    this.panelNext.observer = this.moveNext.bindAsEventListener(this);
    
    if (arImgPath.length > 1) {
      this.panelPrev.observe('click', this.panelPrev.observer);
      this.panelPrev.observe('mousemove', this.panelPrev.mMoveObserver);
      this.panelPrev.observe('mouseout', this.panelPrev.mOutObserver);
      this.panelNext.observe('click', this.panelNext.observer);
      this.panelNext.observe('mousemove', this.panelNext.mMoveObserver);
      this.panelNext.observe('mouseout', this.panelNext.mOutObserver);
    }
    
    
  },
  
  buildDomObj: function() {
    var height = this.imageContainer.height + "px";
    var width = this.imageContainer.width + "px";
    var panelWidth = Math.floor(this.imageContainer.width / 2) + "px";
    this.container.setStyle({"height":height, "width":width});
    
    if (arImgPath.length > 1) {
      this.transpixelPrev.setStyle({"height":height, "width":panelWidth});
      this.transpixelNext.setStyle({"height":height, "width":panelWidth});
    
      this.panelPrev.setStyle({"height":height, "width":panelWidth});
      this.panelNext.setStyle({"height":height, "width":panelWidth});
      
      this.panelPrev.appendChild(this.transpixelPrev);
      this.panelNext.appendChild(this.transpixelNext);
      
      this.container.appendChild(this.btnNext);
      this.container.appendChild(this.btnPrev);
      this.container.appendChild(this.panelNext);
      this.container.appendChild(this.panelPrev);
    } else {
      this.transpixelNext.setStyle({"height":height, "width":width});
      this.container.appendChild(this.transpixelNext);
    }
    
    this.addObservers();
  },
  
  hideNext: function() { this.btnNext.hide(); },
  
  hidePrev: function() { this.btnPrev.hide(); },
  
  moveNext: function() {
    var thisIdx = this.eventImg.idx;
    var nextIdx = thisIdx + 1;
    if (nextIdx == arObjImg.length) { nextIdx = 0; };
    this.optionsPanel.fadeOut();
    arObjImg[nextIdx].optionsPanel.fadeIn();
  },
  
  movePrev: function() {
    var thisIdx = this.eventImg.idx;
    var prevIdx = thisIdx -1;
    if (prevIdx == -1) { prevIdx = arObjImg.length - 1; };
    this.optionsPanel.fadeOut();
    arObjImg[prevIdx].optionsPanel.fadeIn();
  },
  
  showNext: function() {
    if (!this.btnNext.visible()) { this.btnNext.show(); }
    if (this.btnPrev.visible()) { this.hidePrev(); }
  },
  
  showPrev: function() {
    if (!this.btnPrev.visible()) { this.btnPrev.show(); }
    if (this.btnNext.visible()) { this.hideNext(); }
  }
  
});

var orderItem = Class.create(base, {
  init: function(params) {
    this.parent = params.parent;
    this.sizeText = params.sizeText;                              // Textual representation of the item size (8X10 Print)
    this.itemId = params.itemId;                                  // rate card item id
    this.detailId = params.detailId;                              // rate card item details id
    this.border = Boolean(params.border);                         // border toggle
    this.finish = (Boolean(params.finish)) ? params.finish:'';    // finish type
    this.cartItemId = params.cartItemId;                          // cart item id
    this.qty = params.qty;                                        // quantity of prints
    this.img = params.img;                                        // image id
    //this.buyPanel = params.buyPanel;                              // object reference to the buy panel
    
    //this.container = new Element('div', {'class':'contImgOrder'});
    this.container.writeAttribute({"class":"contImgOrder"});
    this.spanQty = new Element('span', {'class':'ordEl ordElQty'});
    this.spanDel = new Element('span', {'class':'ordEl ordElDel', 'title':'Remove from cart'});
    this.imgDel = new Element('img', {'class':'ordDel', 'src':'/templates/sngexposure/images/btn_close.png', 'title':'Remove from cart'});
    this.borderCheck = new Element('img', {'class':'ordBorder', 'src':'/components/com_sngevents/views/event/tmpl/images/checkmark.png'});
    this.spanSizeText = new Element('span', {'class':'ordEl ordElSize'});
    this.spanBorder = new Element('span', {'class':'ordEl ordElBorder'});
    this.spanFinish = new Element('span', {'class':'ordEl ordElFinish'});
  },
  
  addObservers: function() {
    this.imgDel.observer = this.del.bindAsEventListener(this);
    this.imgDel.observe('click', this.imgDel.observer);
  },
  
  del: function(e) {
    //Event.stop(e);
    this.removeFromCart();
  },
  
  flash: function() {
    new Effect.Highlight(this.container, { "startcolor": "#0000FF", "restorecolor": "#FFFFFF", "duration": 2 });
  },
  
  buildDomObj: function() {
    if (this.border) { this.spanBorder.appendChild(this.borderCheck); }
    this.container.appendChild(this.spanQty.update(this.qty));
    this.container.appendChild(this.spanSizeText.update(this.sizeText));
    this.container.appendChild(this.spanBorder);
    this.container.appendChild(this.spanFinish.update(this.finish));
    this.spanDel.appendChild(this.imgDel);
    this.container.appendChild(this.spanDel);
    this.addObservers();
  },
  
  removeFromCart: function() {
    var objThis = this;
    params = {"controller":"cart", "option":"com_sngevents", "task":"remove_from_cart", "photoId":this.img, "eventId":eventId, "cartItemId":this.cartItemId};
    new Ajax.Request('/', {
      method: 'post',
      parameters: params,
      onSuccess: function(transport) {
        var objResponse = transport.responseText.evalJSON(true);
        if (objResponse.arErr.length) {
          var errMsg = "Errors were encountered while attempting to add the item to the cart:";
          objResponse.arErr.each(function(s) { errMsg += "\n - " + s; });
          alert(errMsg);
        } else {
          objThis.parent.repopCart(objResponse.dataResult);
          objThis.parent.reset();
          objThis.parent.populate();
          if (typeof objCartInfoPanel != "undefined") { objCartInfoPanel.setQty("goToServer"); }
        }
      }
    });
  }
});

var snapVideoPlayer = Class.create(base, {
  initialize: function(params) {
    this.container = new Element('video', { "width":"512", "height":"288", "controls":"true" });
    this.source = new Element('source', { "src":params.src, "type":"video/mp4" });
    this.container.appendChild(this.source);
  }
});

/*var widgetComment = Class.create(baseWidget, {
  init: function(params) {
    this.canvas.hide();
    this.xid = "img" + params.imgId;
    //this.canvas.update('Comments - ' + this.xid);
    this.heading  = new Element('h3').update(JText['COMMENT']);
    this.fbComment = new Element('fb:comments', {"xid":this.xid, "width":430, "numposts":10});
    this.buildDomObj();
  },
  
  buildDomObj: function() {
    
    this.canvas.appendChild(this.fbComment);
  }
});*/

var widgetComment = Class.create(baseWidget, {
  init: function(params) {
    //this.canvas.setStyle({"width":"435px"});
    this.heritage = Object.clone(this.parent.heritage);
    this.heritage.widgetComment = this;
    this.itemId = params.imgId;
    this.tid = 1;
    this.iid = params.imgId;
    this.heading  = new Element('h3').update(JText['COMMENT']);
    this.loginNote = new Element('span', {"class":"loginNote"}).update(JText['LOGIN_POST']);
    if (!userId) {
      
    }
    
    this.form = new Element('form');
    this.textField = new widgetComment_field({"parent":this});
    this.comments = new widgetComment_comments({"parent":this});
    
    this.buildDomObj();
  },
  
  buildDomObj: function() {
    if (!userId) { this.canvas.appendChild(this.loginNote); }
    this.canvas.appendChild(this.heading);
    this.canvas.appendChild(this.textField.getDomObj());
    this.canvas.appendChild(this.comments.getDomObj());
  }
});

var widgetEventComment = Class.create(base, {
  init: function(params) {
    this.container.writeAttribute({"class":"contEventComments"});
    this.iid = params.iid;
    this.tid = 2;
    params = (params) ? params:{};
    params.iid = eventId;
    params.tid = 2;
    params.parent = this;
    
    this.heading  = new Element('h3').update(JText['COMMENT_EVENT']);
    this.loginNote = new Element('span', {"class":"loginNote"}).update(JText['LOGIN_POST']);
    this.form = new Element('form');
    this.textField = new widgetComment_field(params);
    this.comments = new widgetComment_comments(params);
    
    this.buildDomObj();
  },
  
  buildDomObj: function() {
    if (!userId) { this.container.appendChild(this.loginNote); }
    this.container.appendChild(this.heading);
    this.container.appendChild(this.textField.getDomObj());
    this.container.appendChild(this.comments.getDomObj());
  }
});

var widgetComment_comment = Class.create(base, {
  init: function(params) {
    this.parent = params.parent;
    this.heritage = Object.clone(this.parent.heritage);
    this.heritage.widgetComment_comment = this;
    this.user = params.s.user_name;
    this.comment = params.s.comment;
    this.cid = params.s.id;
    this.date = params.s.date;
    
    this.contUser = new Element('div', {"class":"cmntUser"});
    this.contComment = new Element('div', {"class":"contComment"});
    this.footer = new Element('div', {"class":"cmntFooter"});
    this.contDate = new Element('span', {"class":"cmntDate"});
    
  },
  
  buildDomObj: function() {
    this.contUser.update(this.user);
    this.contComment.update(this.comment);
    this.contDate.update(this.date);
    
    this.footer.appendChild(this.contDate);
    this.footer.appendChild(new Element('div', {"class":"clear"}));
    
    this.container.appendChild(this.contUser);
    this.container.appendChild(this.contComment);
    this.container.appendChild(this.footer);
  }
});

var widgetComment_comment_opts = Class.create(base, {
  init: function() {
    
  }
});

var widgetComment_comments = Class.create(base, {
  init: function(params) {
    this.container.writeAttribute({"class":"contComments"});
    this.parent = params.parent;
    this.heritage = Object.clone(this.parent.heritage);
    this.heritage.widgetComment_comments = this;
    this.arComments = new Array();
    this.loaded = false;
  },
  
  buildDomObj: function() {
    this.container.appendChild(new Element('div'));
  },
  
  getComments: function() {
    if (!this.loaded) {
      var objThis = this;
      new Ajax.Request('/', {
        method: 'post',
        parameters: {
          option: 'com_sngevents',
          controller: 'comments',
          task: 'get_comments',
          tid: this.parent.tid,
          iid: this.parent.iid
        },
        onSuccess: function(transport) {
          var objResponse = transport.responseText.evalJSON(true);
          if (objResponse.arErr.length) {
            var errList = "";
            objResponse.arErr.each(function(s) {
              errList += s + "\n";
            });
            alert(errList);
          } else {
            for (var i=0; i<objResponse.dataResult.length; i++) {
              objThis.arComments.push(new widgetComment_comment({"parent":objThis, "s":objResponse.dataResult[i]}));
            }
            objThis.loaded = true;
            objThis.populate();
          }
        }
      });  // new AJAX.Request
    }
  },
  
  populate: function() {
    if (!this.loaded) {
      this.getComments();
    } else {
      var objThis = this;
      var counter = 0;
      
      this.container.purge();
      this.arComments.each(function(s) {
        s.container.writeAttribute({"class":"commentBox" + counter});
        objThis.container.appendChild(s.getDomObj());
        counter = (counter) ? 0:1;
      });
    }
  },
  
  reload: function() {
    this.arComments = new Array();
    this.loaded = false;
    this.load();
  }
});

var widgetComment_field = Class.create(base, {
  init: function(params) {
    this.parent = params.parent;
    this.heritage = Object.clone(this.parent.heritage);
    this.heritage.widgetComment_field = this;
    this.name = "ic" + this.parent.itemId;
    //this.tid = (params.tid) ? params.tid:1;  //the table id to which the comment refers
    //this.iid = (this.heritage.eventImg) ? this.heritage.eventImg.id:params.iid; // set item id

    this.btnSubmit = new Element('span', {"class":"commentSubmit"});
    this.spanPost = new Element('span');
    this.contPost = new Element('span', {"class":"commentPostBtn"});
    this.field = new Element('textarea', {"name":this.name, "cols":"37", "rows":"2", "class":"imgCommentField"});
    //this.charCount = new Element('div', {"class":"comCharCount"}).update('255');
    
    if (userId) { this.addObservers(); }
    
  },
  
  addObservers: function() {
    this.field.observer = this.resizer.bindAsEventListener(this);
    
    
    //this.textField.keyupObserver = this.resizer.bindAsEventListener(this);
    this.field.observe('click', this.field.observer);
    this.field.observe('keyup', this.field.observer);
    
    if (userId) {
      this.contPost.observer = this.saveComment.bindAsEventListener(this);
      this.contPost.observe('click', this.contPost.observer);
    }
  },
  
  buildDomObj: function() {
    this.spanPost.update(JText['POST']);
    
    //this.container.appendChild(this.charCount);
    this.contPost.appendChild(this.spanPost);
    this.contPost.appendChild(this.btnSubmit);
    
    if (!userId) {
      //this.contPost.update(JText['LOGIN_POST']);
      this.contPost.setStyle({"cursor":"default", "color":"#C0C0C0"});
      this.field.writeAttribute({"disabled":"true"});
      this.field.setStyle({"backgroundColor":"#EEEEEE"})
    }
    this.container.appendChild(this.contPost);
    this.container.appendChild(this.field);
    this.container.appendChild(new Element('div', {"class":"clear"}));
  },
  
  resizer: function() {
    var lines = this.field.value.split('\n');
    var line = null;
    var newRows = lines.length;
    var oldRows = this.field.readAttribute('rows');
    for (var i = 0; i < lines.length; i++) {
      line = lines[i];
      if (line.length >= this.field.readAttribute('cols')) newRows += Math.floor(line.length / this.field.readAttribute('cols'));
    }
    if (newRows > this.field.readAttribute('rows')) this.field.writeAttribute({"rows":newRows});
    if (newRows < this.field.readAttribute('rows')) this.field.writeAttribute({"rows":Math.max(2, newRows)});
    if (this.field.getValue().length > 255) {
      this.field.setValue(this.field.getValue().substring(0, 254));
      this.resizer();
    }
    //this.charCount.update(255 - this.field.getValue().length);
  },
  
  saveComment: function() {
    if ($F(this.field)) {
      var objThis = this;
      this.contPost.stopObserving('click', this.contPost.observer);
      new Ajax.Request('/', {
        method: 'post',
        parameters: {
          option: 'com_sngevents',
          controller: 'comments',
          task: 'save_comment',
          tid: this.parent.tid,
          iid: this.parent.iid,
          comment: $F(this.field)
        },
        onSuccess: function(transport) {
          var objResponse = transport.responseText.evalJSON(true);
          if (objResponse.arErr.length) {
            var errList = "";
            objResponse.arErr.each(function(s) {
              errList += s + "\n";
            });
            alert(errList);
          } else {
            objThis.field.value = "";
            objThis.parent.comments.arComments = new Array();
            objResponse.dataResult.each(function(s) {
              objThis.parent.comments.arComments.push(new widgetComment_comment({"parent":objThis, "s":s}));
            });
            objThis.parent.comments.populate();
            objThis.contPost.observe('click', objThis.contPost.observer);
          }
        }
      });  // new AJAX.Request
    } else {
      alert('Enter your comment.');
    }
  }
});

var widgetBuyPhoto = Class.create(baseWidget, {
  init: function(params) {
    if (!arBuyOptionListError) {
      this.canvas.hide();
      this.parent = params.parent;
      this.controlContainer = params.parent;
      
      this.heading = new Element('h3').update(JText['ADD_CART']);
      this.cartInfoBox = new Element('div', {"class":"cartInfoBox"});
      this.cartInfo = new Element('div', {"class":"cartInfo"});
      this.btnViewCart = new Element('a', {'class':'payLink', 'href':'/?option=com_sngcart'}).update('View your cart');
      
      this.cartInfoCount = null;
      this.form = new Element('form');
      this.rowSizeQty = new Element('div');
      this.rowBorderFinish = new Element('div', {"class":"borderFinish"});
      
      this.selectSize = new widgetBuy_sizeSelector({"parent":this});
      this.qty = new widgetBuy_qty({"parent":this});
      this.border = new widgetBuy_border({"parent":this});
      this.finish = new widgetBuy_finish({"parent":this});
      this.addCart = new widgetBuy_addCart({"parent":this});
      this.cart = new widgetBuy_cartContent({"parent":this});
      
      this.addObservers();
      this.buildDomObj();
    }
  },
  
  addObservers: function() {
    this.form.observe('submit', function(e) { Event.stop(e); });
  },
  
  buildDomObj: function() {
    this.cartInfoBox.appendChild(this.cartInfo);
    this.cartInfoBox.appendChild(this.btnViewCart);
  
    this.canvas.appendChild(this.cartInfoBox);
    this.canvas.appendChild(this.heading);
    
    this.rowSizeQty.appendChild(this.selectSize.getDomObj());
    this.rowSizeQty.appendChild(this.qty.getDomObj());
    this.rowBorderFinish.appendChild(this.border.getDomObj());
    this.rowBorderFinish.appendChild(this.finish.getDomObj());
    this.rowBorderFinish.appendChild(this.addCart.getDomObj());
    
    this.form.appendChild(this.rowSizeQty);
    this.form.appendChild(this.rowBorderFinish);
    this.canvas.appendChild(this.form);
    this.canvas.appendChild(this.cart.getDomObj());
    
    this.reset();
  },
  
  addToCart: function() {
    if (this.formValid()) {
      var params = {};
      var photoSelectedValue = this.selectSize.getSelectedValue();
      params.rateCardItemId = this.selectSize.getSelectedRateCardItemId();
      params.sizeText = this.selectSize.getSelectedText();
      params.rateCardItemDetailId = this.selectSize.getSelectedValue();
      params.border = this.border.getCheckedValue();
      params.finish = this.finish.getCheckedValue();
      params.qty = this.qty.getValue();
      params.photoId = this.controlContainer.optionsPanel.eventImg.id;
      this.cart.addToCart(params);
      this.reset();
    } else {
      var errMsg = "This item can't be added to the cart:\n";
      if (!this.selectSize.isValid()) {
        errMsg += " - Select a size\n";
      } else {
        if (!this.qty.isValid()) { errMsg += " - Enter a quantity.\n"; }
        if (!this.finish.isValid()) { errMsg += " - Select a finish\n"; }
      }
      alert(errMsg);
    }
  },
  
  reset: function() {
    this.selectSize.selectSizeSelector.selectedIndex = 0;
    this.qty.inputQty.value = "";
    this.qty.disable();
    this.border.cbBorder.checked = true;
    this.border.disable();
    this.finish.rbGlossy.checked = false;
    this.finish.rbMatte.checked = false;
    this.finish.disable();
    this.addCart.disable();
  },
  
  updateCartInfo: function() {
    if ($('cartContentCount')) {
      if (this.cartInfoCount != $('cartContentCount').innerHTML) {
        this.cartInfoCount = $('cartContentCount').innerHTML;
        this.cartInfo.update('Your cart contains ' + this.cartInfoCount + ' item' + $('cartPluralizer').innerHTML + '.');
      }
    }
  },
  
  formValid: function() {
    var valid = true;
    if (!this.selectSize.isValid()) { valid = false; }
    if (!this.qty.isValid()) { valid = false; }
    if (!this.finish.isValid()) { valid = false; }
    return valid;
  }
});

var widgetBuy_addCart = Class.create(base, {
  initialize: function(params) {
    this.parent = params.parent;
    this.widgetBuyPhoto = params.parent;
    this.container = new Element('span', {"class":"contAddCart"});
    this.button = new Element('input', {"type":"button", "value":JText['ADD_CART']});
    
    this.addObservers();
  },
  
  addObservers: function() {
    this.button.observer = this.parent.addToCart.bindAsEventListener(this.parent);
    this.button.observe('click', this.button.observer);
  },
  
  buildDomObj: function() {
    this.container.appendChild(this.button);
  },
  
  disable: function() {
    this.button.disabled = true;
  },
  
  enable: function() {
    this.button.disabled = false;
  }
});

var widgetBuy_border = Class.create(base, {
  initialize: function(params) {
    this.parent = params.parent;
    this.widgetBuyPhoto = params.parent;
    this.container = new Element('span', {"class":"contBorder"});
    this.textLabel = new Element('span', {"class":"buyTextLabel"});
    this.textLabel.update(JText["BORDER"]||"Border");
    this.textLabel.update(this.textLabel.innerHTML + ":");
    this.cbBorder = new Element("input", {"type":"checkbox"});
    this.cbBorder.setStyle({"backgroundColor":"white", "borderWidth":"0px"});
    //this.addObservers();
  },
  
  addObservers: function() {
    this.cbBorder.observer = this.cbClick.bindAsEventListener(this);
    this.cbBorder.observe('click', this.cbBorder.observer);
  },
  
  buildDomObj: function() {
    this.container.appendChild(this.textLabel);
    this.container.appendChild(this.cbBorder);
  },
  
  cbClick: function() {
    this.cbBorder.checked = (this.cbBorder.checked) ? false:true;
  },
  
  disable: function() {
    this.textLabel.addClassName('buyTextLabel_disabled');
    this.cbBorder.disabled = true;
  },
  
  enable: function() {
    this.textLabel.removeClassName('buyTextLabel_disabled');
    this.cbBorder.disabled = false;
  },
  
  getCheckedValue: function() {
    return (this.cbBorder.checked) ? 1:'';
  }
});

var widgetBuy_cartContent = Class.create(base, {
  init: function(params) {
    this.parent = params.parent;
    this.widgetBuyPhoto = params.parent;
    this.controlContainer = this.widgetBuyPhoto.parent;
    this.optionsPanel = this.controlContainer.parent;
    this.eventImg = this.optionsPanel.parent;
    this.loaded = false;
    
    this.container.writeAttribute('class', 'buyImgCart');
    this.header = new Element('div', {'class':'buyImgHdr'});
    this.spanQty = new Element('span', {"class":"hdrLabel buyImgHdrQty", "title":JText['QUANTITY']}).update(JText['QUANTITY']||'Quantity');
    this.spanSize = new Element('span', {"class":"hdrLabel buyImgHdrSize"}).update('Size');
    this.spanBorder = new Element('span', {"class":"hdrLabel buyImgHdrBorder"}).update('Border');
    this.spanFinish = new Element('span', {"class":"hdrLabel buyImgHdrFinish"}).update('Finish');
    this.spanDel = new Element('span', {"class":"hdrLabel buyImgHdrDel", "title":"Remove from cart"}).update('Remove');
    this.contOrders = new Element('div', {"class":"contBuyImgCartList"});
    
    this.arOrdItems = new Array();
  },
  
  buildDomObj: function() {
    this.header.appendChild(this.spanQty);
    this.header.appendChild(this.spanSize);
    this.header.appendChild(this.spanBorder);
    this.header.appendChild(this.spanFinish);
    this.header.appendChild(this.spanDel);
    this.container.appendChild(this.header);
    this.container.appendChild(this.contOrders);
  },
  
  addToCart: function(params) {
    var dupeItem = this.isADuplicate(params);
    var objThis = this;
    if (dupeItem) {
      if (dupeItem.qty != params.qty) {
        params.cartItemId = dupeItem.cartItemId;
        this.updateCart(params);
      } else {
        var topOffset = dupeItem.container.positionedOffset();
        var scrollTo = (topOffset - 45 > 0) ? topOffset - 45:0;
        this.contOrders.scrollTop = scrollTo;
        //dupeItem.container.scrollTo();
        dupeItem.flash();
      }
    } else {
      params.controller = 'cart';
      params.option = 'com_sngevents';
      params.task = 'add_cart';
      //params.photoId = this.currentImg().id;
      params.eventId = eventId;
      new Ajax.Request('/', {
        method: 'post',
        parameters: params,
        onSuccess: function(transport) {
          var objResponse = transport.responseText.evalJSON();
          if (objResponse.arErr.length) {
            var errMsg = "Errors were encountered while attempting to add the item to the cart:";
            objResponse.arErr.each(function(s) { errMsg += "\n - " + s; });
            alert(errMsg);
          } else {
            objThis.repopCart(objResponse.dataResult);
            objThis.reset();
            objThis.populate();
            objThis.loaded = true;
            if (typeof objCartInfoPanel != "undefined") { objCartInfoPanel.setQty("goToServer"); }
          }
        }
      });
    }
  },
  
  getCartContent: function() {
    var objThis = this;
    params = {"controller":"cart", "option":"com_sngevents", "task":"get_cart_items_by_img", "photoId":this.eventImg.id, "eventId":eventId};
    this.widgetBuyPhoto.addCart.disable();
    new Ajax.Request('/', {
      method: 'post',
      parameters: params,
      onSuccess: function(transport) {
        if (!transport.responseText.isJSON()) {
          var objResponse = new Object();
          objResponse.arErr = new Array(transport.responseText);
          objResponse.arDebug = new Array();
        } else {
          var objResponse = transport.responseText.evalJSON();
        }
        if (objResponse.arErr.length) {
          var errMsg = "Some errors were encountered while attempting to retrieve the cart contents:";
          objResponse.arErr.each(function(s) {
            errMsg += "\n  -" + s;
          });
          alert(errMsg);
        } else {
          objThis.repopCart(objResponse.dataResult);
          objThis.reset();
          objThis.populate();
          objThis.loaded = true;
          objThis.parent.updateCartInfo();
        }
        objThis.widgetBuyPhoto.addCart.enable();
      }
    });
  },
  
  isADuplicate: function(params) {
    var alreadyInCart = null;
    params.finish = (params.finish) ? params.finish:"";
    this.arOrdItems.each(function(s) {
      if ((params.rateCardItemDetailId == s.detailId) && (params.rateCardItemId == s.itemId) && (Boolean(params.border) == Boolean(s.border)) && (params.finish == s.finish)) {
        alreadyInCart = s;
      }
    });
    
    return alreadyInCart;
  },
  
  populate: function() {
    this.arOrdItems.each(function(s) { this.contOrders.appendChild(s.getDomObj()); }.bind(this));
  },
  
  repopCart: function(arCartItems) {
    this.arOrdItems.length = 0;
    var objThis = this;
    var thisParams;
    arCartItems.each(function(s) {
      thisParams = s;
      thisParams.parent = this;
      thisParams.img = this.eventImg.id;
      this.arOrdItems.push(new orderItem(thisParams));
    }.bind(this));
  },
  
  reset: function() {
    this.contOrders.purge();
  },
  
  updateCart: function(params) {
    var objThis = this;
    params = (typeof params == "undefined") ? {}:params;
    params.controller = 'cart';
    params.option = 'com_sngevents';
    params.task = 'update_qty';
    new Ajax.Request('/', {
      method: 'post',
      parameters: params,
      onSuccess: function(transport) {
        var objResponse = transport.responseText.evalJSON();
        if (objResponse.arErr.length) {
          var errMsg = "There was an error while attemting to retrieve your cart contents:\n";
          objResponse.arErr.each(function(s) { errMsg += " - " + s + "\n"; } );
          alert(errMsg);
        } else {
          objThis.repopCart(objResponse.dataResult);
          objThis.reset();
          objThis.populate();
          objThis.loaded = true;
        }
      }
    });
  }
});

var widgetBuy_finish = Class.create(base, {
  initialize: function(params) {
    this.parent = params.parent;
    this.widgetBuyPhoto = params.parent;
    this.container = new Element('span', {"class":"contFinish"});
    this.textLabel = new Element('span', {"class":"buyTextLabel"});
    this.textLabel.update(JText["FINISH"]||"Finish");
    this.textLabel.update(this.textLabel.innerHTML + ":");
    this.spanMatte = new Element('span').update(JText['MATTE']||'Matte');
    this.rbMatte = new Element('input', {"type":"radio", "name":"finish", "value":"matte"});
    this.rbMatte.setStyle({"backgroundColor":"white", "borderWidth":"0px"});
    this.labelMatte = new Element('label', {"title":JText['MATTE_TITLE']});
    this.spanGlossy = new Element('span').update(JText['GLOSSY']||'Glossy');
    this.rbGlossy = new Element('input', {"type":"radio", "name":"finish", "value":"glossy"});
    this.rbGlossy.setStyle({"backgroundColor":"white", "borderWidth":"0px"});
    this.labelGlossy = new Element('label', {"title":JText['GLOSSY_TITLE']});
    this.addObservers();
  },
  
  addObservers: function() {
    this.labelMatte.observe('click', function(){ this.rbMatte.checked = true }.bindAsEventListener(this));
    this.labelGlossy.observe('click', function(){ this.rbGlossy.checked = true }.bindAsEventListener(this));
  },
  
  buildDomObj: function() {
    this.labelGlossy.appendChild(this.rbGlossy);
    this.labelGlossy.appendChild(this.spanGlossy);
    this.labelMatte.appendChild(this.rbMatte);
    this.labelMatte.appendChild(this.spanMatte);
    
    this.container.appendChild(this.textLabel);
    this.container.appendChild(this.labelGlossy);
    this.container.appendChild(this.labelMatte);
  },
  
  disable: function() {
    this.textLabel.addClassName('buyTextLabel_disabled');
    [this.labelMatte, this.labelGlossy].each(function(s) { s.setStyle({"color":"#C0C0C0"}); });
    this.rbMatte.disabled = true;
    this.rbGlossy.disabled = true;
  },
  
  enable: function() {
    this.textLabel.removeClassName('buyTextLabel_disabled');
    [this.labelMatte, this.labelGlossy].each(function(s) { s.setStyle({"color":"black"}); });
    this.rbGlossy.disabled = false;
    this.rbMatte.disabled = false;
  },
  
  getCheckedValue: function() {
    var r = null;
    r = (this.rbMatte.checked) ? this.rbMatte.value:r;
    r = (this.rbGlossy.checked) ? this.rbGlossy.value:r;
    return r;
  },
  
  isValid: function() {
    if (this.parent.selectSize.getSelectedRateCardItemId() == 48) {
      return true;
    }
    return ((this.rbGlossy.checked) || (this.rbMatte.checked)) ? true:false;
  }
});

var widgetBuy_qty = Class.create(base, {
  initialize: function(params) {
    this.parent = params.parent;
    this.widgetBuyPhoto = params.parent;
    this.container = new Element('span', {"class":"contQty"});
    this.textLabel = new Element('span', {"class":"buyTextLabel"});
    this.textLabel.update(JText["QUANTITY"]||"Quantity");
    this.textLabel.update(this.textLabel.innerHTML + ":");
    this.inputQty = new Element("input", {"type":"text", "size":"2", "maxlength":"2"});
  },
  
  buildDomObj: function() {
    this.container.appendChild(this.textLabel);
    this.container.appendChild(this.inputQty);
  },
  
  disable: function() {
    this.textLabel.addClassName('buyTextLabel_disabled');
    this.inputQty.disabled = true;
  },
  
  enable: function() {
    this.textLabel.removeClassName('buyTextLabel_disabled');
    this.inputQty.disabled = false;
  },
  
  getValue: function() {
    return this.inputQty.value;
  },
  
  isValid: function() {
    return ((!isNaN(this.inputQty.value)) && (this.inputQty.value > 0)) ? true:false;
  }
});

var widgetBuy_sizeSelector = Class.create(base, {
  initialize: function(params) {
    this.parent = params.parent;
    this.widgetBuyPhoto = params.parent;
    this.container = new Element('span', {'class':'contSizeSelector'});
    this.textLabel = new Element('span', {'class':'buyTextLabel'});
    this.textLabel.update(JText['SELECT_SIZE']||"Select size");
    this.textLabel.update(this.textLabel.innerHTML + ":");
    this.selectSizeSelector = new Element('select', {'class':'sizeSelector', 'name':'sizeSelector'});
    //this.arRateCardItemIds = new Array();
    
    this.populate();
    
    this.addObservers();
  },
  
  addObservers: function() {
    this.changeObserver = this.sizeSelect.bindAsEventListener(this);
    this.selectSizeSelector.observe('change', this.changeObserver);
  },
  
  buildDomObj: function() {
    this.selectSizeSelector.selectedIndex = -1;
    this.container.appendChild(this.textLabel);
    this.container.appendChild(this.selectSizeSelector);
  },
  
  getSelectedIndex: function() {
    return this.selectSizeSelector.selectedIndex;
  },
  
  getSelectedOption: function() {
    return this.selectSizeSelector.options[this.getSelectedIndex()]
  },
  
  getSelectedRateCardItemId: function() {
    return this.getSelectedOption().retrieve('rateCardItemId');
  },
  
  getSelectedText: function() {
    return this.getSelectedOption().text;
  },
  
  getSelectedValue: function() {
    return this.getSelectedOption().value;
  },
  
  isValid: function() {
    if (this.selectSizeSelector.selectedIndex > 0) { return true; } else { return false; }
  },
  
  populate: function() {
    var thisOptionIdx = null;
    this.selectSizeSelector.options[0] = new Option('', '');
    arBuyOptionList.each(function(s) {
      thisOptionIdx = this.selectSizeSelector.options.length
      this.selectSizeSelector.options[thisOptionIdx] = $(new Option(s.text, s.rateCardItemDetailId));
      this.selectSizeSelector.options[thisOptionIdx].store('rateCardItemId', s.rateCardItemId);
    }.bind(this));
  },
  
  sizeSelect: function() {
    var selectedOption = this.selectSizeSelector.options[this.selectSizeSelector.selectedIndex];
    if (selectedOption.text == "") {
      this.parent.qty.inputQty.value = "";
      this.parent.qty.disable();
      this.parent.border.disable();
      this.parent.finish.disable();
      this.parent.addCart.disable();
    } else {
      this.parent.addCart.enable();
      //if (selectedOption.readAttribute('rciid') == 48) {  // 48 is the ID for a downloadable file
      if (selectedOption.retrieve("rateCardItemId") == 48) { // 48 is the ID for a downloadable file
        this.parent.qty.inputQty.value = 1;
        this.parent.qty.disable();
        this.parent.border.cbBorder.checked = false;
        this.parent.border.disable();
        this.parent.finish.rbGlossy.checked = false;
        this.parent.finish.rbMatte.checked = false;
        this.parent.finish.disable();
      } else {
        this.parent.qty.enable();
        this.parent.border.enable();
        this.parent.finish.enable();
      }
    }
  }
});

var widgetShare = Class.create(baseWidget, {
  init: function(params) {
    this.canvas.hide();
    this.parent = params.parent;
    this.heritage = Object.clone(this.parent.heritage);
    this.heritage.widgetShare = this;
    params.parent = this;
    //params.heritage = this.heritage;
    
    this.heading = new Element('h3').update(JText['SHARE']);
    this.fbShare = new widgetShare_fb(params);
    this.twShare = new widgetShare_tw(params);
    this.emailShare = new widgetShare_email(params);
    this.buildDomObj();
  },
  
  buildDomObj: function() {
/*<fb:share-button class="meta">
<meta name="title" content="[ TITLE ]" />
<meta name="description" content="[ DESCRIPTION ]" />
<link rel="image_src" href="[ IMAGE URL ]" />
<link rel="target_url" href="[ LINK URL ]" />
</fb:share-button>*/
    this.canvas.appendChild(this.heading);
    this.canvas.appendChild(this.fbShare.getDomObj());
    this.canvas.appendChild(this.twShare.getDomObj());
    this.canvas.appendChild(this.emailShare.getDomObj());
  }
});

var widgetShare_fb = Class.create(base, {
  init: function(params) {
    this.container.writeAttribute({"class":"shareRow"});
    this.parent = params.parent;
    this.widgetShare = params.parent;
    this.heritage = Object.clone(this.parent.heritage);
    this.shareUrl = this.heritage.eventImg.fbLink;
    this.spanShareText = new Element('span', {"class":"shareSpanShareText"}).update(JText['FB_SHARE_PHOTO']);
    var pageTitle = document.getElementsByTagName("title")[0].innerHTML;
    
    var protocol = location.protocol;
    var host = location.host;
    var objQuery = location.href.toQueryParams();
    var shareTitle = "Photo taken at " + pageTitle;
    var description = (this.heritage.optionsPanel.contImage.captionText) ? this.heritage.optionsPanel.contImage.captionText:shareTitle;
    
    this.shareBtn = new Element('fb:share-button', {"class":"url", "type":"button", "href":this.shareUrl});
    this.title = new Element('meta', {"name":"title", "content":shareTitle});
    this.description = new Element('meta', {"name":"description", "content":description});
    this.image_src = new Element('link', {"rel":"image_src", "href":this.heritage.eventImg.imgSmall.readAttribute('src')});
    this.target_url = new Element('link', {"rel":"target_url", "href":this.shareUrl});
  },
  
  buildDomObj: function() {
    //this.shareBtn.appendChild(this.medium);
    this.shareBtn.appendChild(this.title);
    //this.shareBtn.appendChild(this.type);
    this.shareBtn.appendChild(this.description);
    this.shareBtn.appendChild(this.image_src);
    this.shareBtn.appendChild(this.target_url);
    //this.shareBtn.appendChild(this.ogTitle);
    //this.shareBtn.appendChild(this.ogImage);
    this.container.appendChild(this.shareBtn);
    this.container.appendChild(this.spanShareText);
    this.container.appendChild(new Element('div', {"class":"clear"}));
  }
});

var widgetShare_tw = Class.create(base, {
  init: function(params) {
    this.container.writeAttribute({"class":"shareRow"});
    var pageTitle = document.getElementsByTagName("title")[0].innerHTML;
    this.parent = params.parent;
    this.widgetShare = params.parent;
    this.heritage = Object.clone(this.parent.heritage);
    this.shortUrl = this.heritage.eventImg.twLink;
    this.twitterStatus = this.shortUrl + " " + pageTitle;
    this.logo = new Element('img', {"src":"/components/com_sngevents/views/event/tmpl/images/twitter_logo.png", "class":"shareImgTweet"});
    this.spanTweet = new Element('span', {"class":"shareSpanTweet"}).update(JText['TWEET']);
    this.spanTweetText = new Element('span', {"class":"shareSpanTweetText"}).update(JText['TWEET_PHOTO']);
    this.spanButtonBox = new Element('span', {"class":"twitterButtonBox"});
    
    this.link = "http://twitter.com/?status=" + this.twitterEncode();
    this.anchor = new Element("a", {"href":this.link, "target":"_blank"});
    
    this.addObservers();
  },
  
  addObservers: function() {
    this.anchor.observer = this.twitterWindow.bindAsEventListener(this);
    this.anchor.observe('click', this.anchor.observer);
  },
  
  twitterWindow: function(e) {
    if ((!twitterWindow) || (twitterWindow.closed)) {
      twitterWindow = window.open(this.link, 'twitterWindow');
    } else {
      twitterWindow.location.replace(this.link);
    }
    //Event.stop(e);
  },
  
  buildDomObj: function() {
    this.spanButtonBox.appendChild(this.logo);
    this.spanButtonBox.appendChild(this.spanTweet);
    this.anchor.appendChild(this.spanButtonBox);
    this.container.appendChild(this.anchor);
    this.container.appendChild(this.spanTweetText);
  },
  
  twitterEncode: function() {
    if (this.twitterStatus.length > 140) {
      this.twitterStatus = this.twitterStatus.substring(0, 136) + "...";
    }
    return escape(this.twitterStatus);
  }
});

var widgetShare_email = Class.create(base, {
  init: function(params) {
    this.container.writeAttribute({"class":"shareRow"});
    this.parent = params.parent;
    this.widgetShare = params.parent;
    this.heritage = Object.clone(this.parent.heritage);
    
    this.logo = new Element('img', {"src":"/components/com_sngevents/views/event/tmpl/images/icon_email.png", "class":"shareImgTweet"});
    this.spanEmail = new Element('span', {"class":"shareSpanEmail"}).update(JText['EMAIL']);
    this.spanEmailText = new Element('span', {"class":"shareSpanEmailText"}).update(JText['EMAIL_SHARE_PHOTO']);
    if (!userId) { this.spanEmailText.update(JText['EMAIL_SHARE_PHOTO_LOGIN']); }
    this.spanButtonBox = new Element('span', {"class":"emailButtonBox"});
    
    this.addObservers();
  },
  
  addObservers: function() {
    if (userId) {
      this.spanButtonBox.observer = this.showMailer.bindAsEventListener(this);
      this.spanButtonBox.observe('click', this.spanButtonBox.observer);
    } else {
      //this.spanButtonBox.setStyle({"cursor":"default"});
      this.spanButtonBox.observe('click', function() {
        //hidePanels();
        var alertMsg = 'You need to log in before you can send email messages.';
        if (confirm(alertMsg)) {
          this.heritage.optionsPanel.fadeOut(true);
          window.scrollTo(0, 0);
          new Effect.Pulsate($('loginBox'), {pulses: 3, duration: 2, afterFinish: function() { $('modlgn_username').focus(); }});
        }
      }.bindAsEventListener(this));
    }
  },
  
  buildDomObj: function() {
    this.spanButtonBox.appendChild(this.logo);
    this.spanButtonBox.appendChild(this.spanEmail);
    //this.anchor.appendChild(this.spanButtonBox);
    this.container.appendChild(this.spanButtonBox);
    this.container.appendChild(this.spanEmailText);
  },
  
  showMailer: function() {
    var presetHTML = '<div style="font-size:14px;margin:5px 0px;padding-top:15px;border-top:1px solid black">';
    presetHTML += '<a href="' + this.heritage.eventImg.emLink + '" style="margin:0px 5px 5px 0px;color: black;float:left" target="_blank"><img src="' + this.heritage.eventImg.imgSmall.readAttribute('src') + '" border="0" width="145" style="float:left;margin-right: 8px;width:145px" /></a>';
    presetHTML += '<div style="font-weight: bold"><a href="' + this.heritage.eventImg.emLink + '" style="margin:0px 5px 5px 0px;color: black" target="_blank">' + document.getElementsByTagName('title')[0].innerHTML + '</a></div>';
    if (this.heritage.eventImg.caption) { presetHTML += '<div style="margin-top: 10px;">' + this.heritage.eventImg.caption + '</div>'; }
    presetHTML += '<div style="clear:both"></div></div>';
  
    document.stopObserving('click', hidePanels);
    SNAPMailer.show({"width":"450px"});
    SNAPMailer.contMessagePreset.update(presetHTML);
    SNAPMailer.presetMessage = presetHTML;
    SNAPMailer.inputSubject.value = document.getElementsByTagName('title')[0].innerHTML;
    SNAPMailer.inputMessage.field.value = "Hi, I thought you might want to take a look at this image.";  
  }
});

function eventCommentsInit() {
  if ($('eventComments')) {
    eventCommenter = new widgetEventComment({"iid":eventId});
    $('eventComments').appendChild(eventCommenter.getDomObj());
    eventCommenter.comments.getComments();
  }
}

function eventInit() {
  imageHandlers();
  eventCommentsInit();
  
  if (eventVideo) { buildVideoPlayer(); }
  imgLoading.hide();
  canvasOverlay.container.hide();
  canvasOverlay.container.purge();
  canvasOverlay.container.setStyle({"backgroundColor":"#303030"});
  document.observe('click', hidePanels);
  loadFacebook();
  eventFbParse();
  if (SNAPMailer) {
    SNAPMailer.btnX.observe('click', function() { document.observe('click', hidePanels); });
    SNAPMailer.onHide = function() {
      document.observe('click', hidePanels);
    }
  }
}

function eventFbParse() {
  if (eventFbCounter < 1000) {
    if (!fbInitialized) {
      setTimeout(function() { eventFbParse(); }, 100);
      eventFbCounter++;
    } else {
      fbParseImages();
      FB.XFBML.parse($('fbEventComments'));
      
    }
  } else {
    alert("The Facebook library is taking too long to load.");
  }
}

function eventDomInit() {
  if (eventDomInitCounter < 100) {
    if (typeof canvasOverlay == "undefined") {
      eventDomInitCounter++;
      setTimeout(function() { eventDomInit(); }, 10);
    } else {
      var imgTop = Math.floor(document.viewport.getHeight() - 25);
      imgTop += "px";
      imgLoading.setStyle({"position":"fixed", "top": imgTop, "left":"0px", "height":"25px", "width":"25px"});
      canvasOverlay.container.setStyle({"backgroundColor":"transparent"});
      canvasOverlay.show();
      document.getElementsByTagName('body')[0].appendChild(imgLoading);
      loadBuyOptions();
      SNAPMailer = new dlgEmail();
      document.body.appendChild(SNAPMailer.getDomObj());
    }
  } else {
    if (typeof canvasOverlay != "undefined") {
      var imgTop = Math.floor(document.viewport.getHeight() - 25);
      imgTop += "px";
      imgLoading.setStyle({"position":"fixed", "top": imgTop, "left":"0px", "height":"25px", "width":"25px"});
      canvasOverlay.container.setStyle({"backgroundColor":"transparent"});
      canvasOverlay.show();
    }
    loadBuyOptions();
    if (userId) { SNAPMailer = new dlgEmail(); }
    document.body.appendChild(SNAPMailer.getDomObj());
  }  
}

function fbParseImages() {
  arObjImg.each(function(s) {
    FB.XFBML.parse(s.container);
  });
}

function hidePanels(e) {
  var evtEl = Event.element(e);
  if ((evtEl.tagName != 'INPUT') && (evtEl.tagName != 'TEXTAREA')) {
    arObjImg.each(function(s) { s.optionsPanel.fadeOut(true); });
  }
}

function imageHandlers() {
  if (arBuyOptionListError === null) {
    setTimeout(function() { imageHandlers() }, 10);
  } else {
    arObjImg.push(new eventImg({"container":$('contArticleImg'), "imgData":arImgPath[0]}));
    var arMoreSnaps = $$('div#imgCanvas span.outerImg');
    for (var i=1; i<arImgPath.length; i++) {
      arObjImg.push(new eventImg({"container":arMoreSnaps[i-1], "imgData":arImgPath[i]}));
    }
    if (arImgPath.length == 1) {
      $('imgCanvas').hide();
    }
    imgPopup();
  }
}

function imgPopup() {
  var popImg = objQuery.i || objQuery.photoId;
  if (popImg) {
    arObjImg.each(function(s) { if (s.id == popImg) { s.optionsPanel.show(); } });
  }
}

function inBoxStop(e) {
  var evtEl = Event.element(e);
  if ((evtEl.tagName != 'INPUT') && (evtEl.tagName != 'TEXTAREA') && (evtEl.tagName != 'A')) { Event.stop(e); }
}

function buildVideoPlayer() {
  var videoURL = eventVideo;
  
  if (Prototype.Browser.IE || (navigator.plugins && navigator.plugins["Shockwave Flash"]) || navigator.plugins["Shockwave Flash 2.0"]) {
    params = {
      plugins: {
        controls: {
          autoHide: "always",
          background: "#FF0000",
          backgroundGradient: 'low',
          timeColor: '#FF0000', //	 Value for the font color in the time field. This is the running time.
          durationColor: '#ffffff', //	 Value for the font color in the time field that specifies the total duration of the clip or "total time".
          progressColor: '#F13F3E', //	 Color of the progress bar. This is the bar in the timeline from zero time to the point where playback is at a given time.
          progressGradient: 'medium', //	Gradient setting for the progress bar. See below for its valid values.
          bufferColor: '#800000', //	 Color of the buffer. The buffer is the bar that indicates how much video data has been read into the player's memory.
          bufferGradient: 'medium', //	Gradient setting for the buffer. See below for its valid values.
          sliderColor: '#555555', //	 Background color for the timeline before the buffer bar fills it. The same background color is also used for the volume slider.
          sliderGradient: 'medium', //	Gradient setting for the sliders. See below for valid values.
          buttonColor: '#C50000', //	Color of the player buttons: stop, play, pause and fullscreen.
          buttonOverColor: '#999999', //	Button color when the mouse is positioned over them
          volumeSliderColor: '#000000', //	Background color for the volume slider (since 3.1)
          volumeSliderGradient:	'medium', //	Volume slider background color gradient (since 3.1). See below for its valid values.
          timeBgColor: '#000000' //	Background color for the time/duration display (since 3.1). You can set timeBgColor: null here and the time area background area will not be drawn at all.
        },
        "pseudo": { url: "/video/dist/flowplayer.pseudostreaming.swf" },
        "openAdStreamer": {
          "url": '/video/dist/OpenAdStreamer.swf',
          "providers": { "http": "pseudo" },
		  "autoPlay": true,
          "shows": { "streams": [ { "file":videoURL, "duration":videoTime } ] },
          "ads": {
            "playOnce": true,
            "servers": [ { "type": "OpenX", "apiAddress": "http://ads.snapnewspapers.com/delivery/fc.php", "disableControls": true } ],
            "schedule": [ {
              "zone": vidZone,
              "position": "pre-roll",
              "notice": { "show": false }
            } ]
          }
        }
      }
    }
    objEventVideo = flowplayer("evtVideo", {src:"/video/dist/flowplayer.swf", wmode:'transparent'}, params);
    
  } else {
    objEventVideo = new snapVideoPlayer({ "src":videoURL });
    $('evtVideo').appendChild(objEventVideo.container);
  }
}

function loadBuyOptions() {
  new Ajax.Request('/', {
    method: 'post',
    parameters: {
      option: 'com_sngevents',
      controller: 'cart',
      task: 'get_option_list'
    },
    onSuccess: function(transport) {
      var objResponse = transport.responseText.evalJSON(true);
      if (objResponse.arErr.length) {
        var errList = "";
        objResponse.arErr.each(function(s) {
          errList += s + "\n";
        });
        alert(errList);
        arBuyOptionListError = objResponse.arErr;
      } else {
        var optText = "";
        objResponse.dataResult.each(function(s) {
          optText = s.optionText + ' (' + s.cost + ')';
          arBuyOptionList.push({"text":optText, "rateCardItemId":s.rateCardItemId, "rateCardItemDetailId":s.rateCardItemDetailId});
        });
        arBuyOptionListError = false;
      }
    },
    onFailure: function() {
      arBuyOptionListError = ["Server Error"];
      alert("There was an error communicating with the server.\nThe image ordering feature will not be enabled.");
    }
  });
}

var arObjImg = new Array();
var arBuyOptionList = new Array();
var arBuyOptionListError = null;
var eventCommenter = null;
var eventDomInitCounter = 0;
var eventFbCounter = 0;
var imgLoading = new Element('img', {"src":"/components/com_sngevents/views/event/tmpl/images/loading.gif"});
var JText = (typeof(JText) == 'undefined') ? {}:JText;
var objQuery = location.href.toQueryParams();

var twitterWindow = null;


Event.observe(window, "load", eventInit);
document.observe("dom:loaded", eventDomInit);

/***********************************************************************************************
|--eventImg
  |
  |--.optionsPanel [optionsPanel]
    |
    |--.contImage [imageContainer]
    | |
    | |--closeButton
    | |--imgIndexController
    | |--captionPanel
    |
    |--.controlCanvas [controlContainer]
      |
      |--widgetComment (childOf baseWidget)
      |--.buy [widgetBuyPhoto] (childOf baseWidget) 
      | |--widgetBuy_sizeSelector
      | |--widgetBuy_qty
      | |--.cart [widgetBuy_cartContent]
      |
      |--.share widgetShare (childOf baseWidget)
        |--.fbShare [widgetShare_fb] (childOf base)
        |--.twShare [widgetShare_tw] (childOf base)

***********************************************************************************************/