/*
  Copyright (c) 2006-2009, ePages GmbH
  All Rights Reserved.

  epages.cartridges.de_epages.design.widget.ProductImages $Revision: 1.19 $

*/

dojo.provide('epages.cartridges.de_epages.product.widget.ProductImages');
dojo.require('epages.widget.LocalizedWidget');
dojo.require('epages.io.json');
dojo.require('epages.string');
epages.require('ep_mediagallery', 'epages.cartridges.de_epages.mediagallery.widget.Mediagallery');

(function(jq){

dojo.declare(
  "epages.cartridges.de_epages.product.widget.ProductImages",
  [epages.widget.LocalizedWidget],
  {
    /**
     * public properties
     */
    objectId            : "",
    uploadAction        : "",
    scaleParams         : "",
    siteId              : epages.vars.SiteID,
    url                 : '?',
    setProductImages    : true,
    multiSelect         : "true",
    big                 : "true",
    reloadAfterUpload   : "true",
    filePath            : "",
    fileAttribute       : "",
    fileName            : "",
    infoText            : "",
    confirm             : "",
    objectId            : epages.vars.ObjectID || '',

    deleteAction        : undefined,
    deleteWidgetDojoType: 'epages.widget.DeleteFileAttributesOnServer',

    /**
     * template properties
     */

    templateType       : 'default',
    defaultTemplateType: 'default',
    _templateMapping: {
      'default'     : {templatePath: dojo.moduleUrl('epages.cartridges.de_epages.product.widget', 'templates/ProductImages.html')},
      'withpreview' : {templatePath: dojo.moduleUrl('epages.cartridges.de_epages.product.widget', 'templates/ProductImagesWithPreview.html')}
    },

    templatePath       : dojo.moduleUrl('epages.cartridges.de_epages.product.widget' , 'templates/ProductImages.html'),
    translationName    : dojo.moduleUrl('epages.cartridges.de_epages.product.widget' , 'templates/translation'),
    /**
     * widget properties
     */
    imagePath         : epages.themeUrl('images'),
    widgetsInTemplate : true,

    postMixInProperties: function() {
      this._templateDirectory = dojo.moduleUrl('epages.cartridges.de_epages.product.widget','templates');
      this.inherited("postMixInProperties", arguments);
      this.uploadAction = this.uploadAction+'&'+this.scaleParams;
      this.setProductImages = epages.string.toBoolean(this.setProductImages);
    },

    postCreate: function() {
      this.inherited("postCreate", arguments);

       if(this.slidesWidgetIns && this.filePath && this.fileName) {
         this.slidesWidgetIns.image = this.filePath + this.fileName;
       }

      if (this.deleteNode) {
         this.deleteNode.onSuccess = dojo.hitch(this, 'onDelete');
          if(this.deleteAction) {
            this.deleteNode.changeAction = deleteAction;
          }
      }

        // set id for uploader
        this.uploadAppletNode.id = this.id+'_uploader';
        dojo.subscribe(this.uploadAppletNode.id + "/onUploadFinished", this, 'onUploadProductImage');
        if (this.deleteNode) {
          this.deleteNode.onSuccess = dojo.hitch(this, 'onDelete');
        }

        var self = this,
          ViewAction = /(?:^|\?|&)ViewAction=(.*?)(?:&|$)/.exec(this.uploadAction);

	      if(!this.hideUploader){
	        de_epages(this.uploadAppletNode)
	          .presentationUiUploader({
	            url:    this.uploadAction+'&'+this.scaleParams,
	            data:   {
	              'ViewAction': ViewAction ? ViewAction[1] : 'JSONViewResponse'
	            },
	            multiple: this.multiSelect,
	            accept:   'image/*',
	            callback: this.reloadAfterUpload==='true' || this.reloadAfterUpload===true ? '?ViewAction='+ep.config.viewAction+'&ObjectID='+ep.config.objectId : function( data ){
	              dojo.publish( self.uploadAppletNode.id + '/onUploadFinished', [data[0].success || data[0].ERROR || {}] );
	            }
	          });
	      }

    },

    onDelete: function() {
      this.nameNode.style.display = 'none';
      this.infoNode.style.display = 'none';
      this.removeImage();
      if (this.fileInputNode) {
        this.fileInputValue = '';
        this.fileInputNode.value = '';
        epages.event.fire(this.fileInputNode, 'change');
      }
      if(this.deleteNode) {
        dojo.addClass(this.deleteNode.domNode, 'HideElement');
      }
      dojo.publish(this.id + '/delete');
    },

    removeImage: function() {
      // summary:
      //    set empty image (hide the current image)
      if(this.slidesWidget) {
        this.slidesWidget.addImage({image: epages.vars.IconsRoot + "/general_img_transparentpixel.gif"}, true);
      }
    },


    _openMediaGallery: function(/*Event*/evt) {
      var MediaGallery = $$('MediaGallery');
      // set onApply function
      var me = this;
      var onApply = function(selectedElements) {
        if(selectedElements.length>0) {
          me._setFileForProduct(selectedElements);
        }
        };
      if(MediaGallery === undefined) {
        MediaGallery = new epages.cartridges.de_epages.mediagallery.widget.Mediagallery({
          id:               'MediaGallery',
          siteId:           this.siteId,
          url:              this.url,
          applyButtonLabel: this.translate('Apply'),
          multiSelect:      this.multiSelect,
          onApply:          onApply
        });
        document.getElementsByTagName("body")[0].appendChild(MediaGallery.domNode);
      } else {
        MediaGallery.multiSelect = this.multiSelect;
        MediaGallery.setOnApply(onApply);
      }
      MediaGallery.show();
    },

    /**
     * events & messages
     */

    onUploadProductImage: function(response) {
      if(this.slidesWidget && response.uploadedFile) {
        var slidesFile;
        slidesFile = response.uploadedFile;

        if(this.filePath && slidesFile) {
          var responseFullFilename = this.filePath + slidesFile;
          this.slidesWidget.addImage({image: responseFullFilename}, true);
          if(this.nameNode) {
            this.nameNode.innerHTML = slidesFile;
          }
          if(this.deleteNode) {
            this.deleteNode.fileName = slidesFile;
            this.deleteNode.filePath = this.filePath;
            this.deleteNode.domNode.style.display = '';
            dojo.removeClass(this.deleteNode.domNode, 'HideElement');
          }
        }
      }
    },

    /**
     * private methods
     */
    _setFileForProduct: function(filesArray){
      dojo.publish("uimessage/startBusy", ["Toolproductimages", this.translate('CopyImageFromMediagallery')]);
      for( var i=0,iLength=filesArray.length ; i<iLength ; i++ ){
        if(this.setProductImages && filesArray[i].mimetype.search(/image/) == -1){
          dojo.publish("uimessage/stopBusy", ["Toolproductimages"]);
          //check if file is an image if setProductImages is activated
          dojo.publish("uimessage/show", [ this.translate('FileNoImage'), this.translate('SelectImage'), 'Dialog', {
              titleBar: this.translate('MediaGallery')+" &ndash; "+this.translate('Notification'),
              typeClass: 'Warning'
            }
          ]);
          return;
        }
        var json = new epages.io.Json;
        var tempParams = this.scaleParams.split('&');
        var scaleParams = {};
        for( var j=0,jLength=tempParams.length ; j<jLength ; j++ ){
          var el = tempParams[j].split('=');
          scaleParams[el[0]] = el[1];
        }
        var params = {
          'ChangeAction': 'MoveAndScaleImage',
          'ObjectID':   this.objectId,
          'File':  filesArray[i].path
        };
        if(this.setProductImages){
          params['SetFilesForProduct'] = true;
        }
        var result = json.loadSync(this.url,dojo.mixin(params,scaleParams));
      }
      dojo.publish("uimessage/stopBusy", ["Toolproductimages"]);
      if (epages.string.toBoolean(this.reloadAfterUpload)){
        var dialogArea = actualDialogArea ? "DialogArea=" + actualDialogArea : "";
        if(location.href.search(/DialogArea/) != -1){
          var newLocation = location.href;
          for( var i=0,iLength=epagesDialog.areaName.length ; i<iLength ; i++ ){
            var regEx = new RegExp('DialogArea='+epagesDialog.areaName[i]);
            newLocation = newLocation.replace(regEx,dialogArea);
          }
          location.href = newLocation;
        }
        else{
          if(dialogArea == ''){
            location.href = location.href;
          }
          else{
            location.href = location.href + '&'+dialogArea;
          }
        }
      }
    }
});

})(jQuery);