
//Ext.onReady(function(){
Ext.QuickTips.init();

//})

function showMessage(title, msg){
	Ext.MessageBox.alert(title, msg);
};

function showMessages(response){
    var resp = Ext.decode(response.responseText);
    if (resp.is_error) {
        var msg = '';
        for(var i=0; i<resp.messages.length; i++){
//            msg += resp.messages[i] + '<br />';
            msg += resp.messages[i];
        }
        setTimeout(this.showMessage.createDelegate(this, ['Info', msg]), 10);
        return true;
    }
    if(resp.messages){
        if(resp.messages.length > 0){
            var msg = '';
            for(var i=0; i<resp.messages.length; i++){
//                msg += resp.messages[i] + '<br />';
                msg += resp.messages[i];
            }
            setTimeout(this.showMessage.createDelegate(this, ['Message', msg]), 10);
            return false;
        }
    }
	return false;
};


function _getSelector(){

	var sm = this.getSelectionModel();
	var store = this.getStore();
	var selected = sm.selections.keys;
	var buttons = (this.buttons)?this.buttons:[];
	var selCount = sm.getCount();

	for (var i=0; i<buttons.length; i++){
	  if(buttons[i].selection != '-'){
		switch (selCount) {
			case 0:
				{
					buttons[i].setDisabled(true);
					if('0' == buttons[i].selection){
						buttons[i].setDisabled(false);
					}
				}
				break;
			case 1:
				{
			    	buttons[i].setDisabled(false);
				}
				break;
			default:
				{
					buttons[i].setDisabled(true);
					if (('N' == buttons[i].selection) || ('0' == buttons[i].selection)) {
						buttons[i].setDisabled(false);
					}
					break;
				}
		}
		if (buttons[i].enablerFunc && typeof buttons[i].enablerFunc == 'function') {
			if (!buttons[i].enablerFunc.call(this, buttons[i])) {
				buttons[i].setDisabled(true);
			}else{
				buttons[i].setDisabled(false);
			}
		}
		}
	}
};

function _getSelectorObject(AObj){
  if (!AObj)
    return;
	var sm = AObj.getSelectionModel();
	var store = AObj.getStore();
	var selected = sm.selections.keys;
	var buttons = (AObj.buttons)?AObj.buttons:[];
	var selCount = sm.getCount();

	for (var i=0; i<buttons.length; i++){
		switch (selCount) {
			case 0:
				{
					buttons[i].setDisabled(true);
					if('0' == buttons[i].selection){
						buttons[i].setDisabled(false);
					}
				}
				break;
			case 1:
				{
			    	buttons[i].setDisabled(false);
				}
				break;
			default:
				{
					buttons[i].setDisabled(true);
					if (('N' == buttons[i].selection) || ('0' == buttons[i].selection)) {
						buttons[i].setDisabled(false);
					}
					break;
				}
		}
		if (buttons[i].enablerFunc && typeof buttons[i].enablerFunc == 'function') {
			if (!buttons[i].enablerFunc.call(this, buttons[i])) {
				buttons[i].setDisabled(true);
			}else{
				buttons[i].setDisabled(false);
			}
		}
	}
};

// Add the additional 'advanced' VTypes
Ext.apply(Ext.form.VTypes, {
  password : function(val, field){
    if (field.initialPassField){
      var pwd = Ext.getCmp(field.initialPassField);
      return (val == pwd.getValue());
    }
    return true;
  },
  passwordText : 'Passwords do not match'
});
Ext.apply(Ext.form.VTypes, {
  phone: function(){
    var re =  /^[\(\d\)-]{0,20}$/;
    return function(v) { return re.test(v); }
  }(),
  phoneText: 'The format is wrong, ie: (123)-456-7890 (dashes optional)'
});

Ext.apply(Ext.form.VTypes, {
  email_uniq: function(){
    Ext.Ajax.request({
       url: 'ajax_check_email.php',
          //method: 'post',
        params: data,
        success: function(response, action) {
          var data = Ext.decode(response.responseText);
          if (data.is_error){

            var msg = '';
            for (var i = 0, mLen = data.messages.length; i < mLen; i++){
              msg += data.messages[i] + '<br />';
            }
            Ext.MessageBox.alert('Warning', msg);
            return false;
          } else
            return true;
        },
        scope: this
    });
  },
  email_uniqText: 'User with this email alredy exists in our system'
});

Ext.override(Ext.ToolTip,{

    adjustPosition : function(x, y){

        // do not position outside the Window
        var cw = document.documentElement.clientWidth-5;
        var ch = document.documentElement.clientHeight-5;
        var bw = this.body.getTextWidth();
        if(this.title) bw = Math.max(bw, this.header.child('span').getTextWidth(this.title));
        bw += this.getFrameWidth() + (this.closable ? 20 : 0) + this.body.getPadding("lr");
        var bh = this.getInnerHeight() + this.getFrameHeight() + this.body.getPadding("tb");
        if(x + bw > cw) x = cw - bw;
        if(y + bh > ch) y = ch - bh;

        // do not position under mousecursor
        var ay = this.targetXY[1], h = this.getSize().height;
        if(this.constrainPosition && y <= ay && (y+h) >= ay){
            y = ay-h-5;
        }

        return {x : x, y: y};
    }

});


//==============================================================================
// Window and Form for uploading images and files

var FileUploadWin = null;

function FileUploadWinShow(AFileType, AUrl, ADlg, AIpId, AOfferType){

  var Dlg = ADlg;

  var FileUploadForm = new Ext.FormPanel({
      fileUpload: true,
      url: AUrl,
      width: 500,
      frame: false,
      autoHeight: true,
      bodyStyle: 'padding: 10px 10px 0 10px;',
      labelWidth: 100,
      defaults: {
        anchor: '95%',
        msgTarget: 'side'
      },
      items: [{
          xtype: 'textfield',
          fieldLabel: 'Caption',
          allowBlank: true,
          name: 'caption',
          id: 'caption'
        },{
          xtype: 'fileuploadfield',
          name: 'file_upload',
          id: 'file_upload',
          emptyText: 'Select a File',
          allowBlank: false,
          fieldLabel: 'File Name',
          buttonCfg: {
            text: '',
            iconCls: 'ico_upload'
          }
        }
      ]
    });

    var funcUpload = function(AReplace){
      var form = FileUploadForm.getForm();
	  var replace;
	  if (AReplace)
        replace = 1;
      else
        replace = 0;

      form.submit(
        {
          params: {
            action: 'upload_files',
            user_id: UserId,
            type: AFileType,
            offer_type: AOfferType,
            offer_id: AIpId,
            replace: replace
          },
          waitMsg: 'Uploading your file...',
          failure: function(frm, act){
            var data = Ext.decode(act.response.responseText);
            Ext.Msg.alert('Failure', data.messages);
          },
          success: function(frm, act){
            var data = Ext.decode(act.response.responseText);
            if (data.type == 'img'){
			  if (Dlg.storeImages){
			    Dlg.storeImages.reload();
              }
			  if (Dlg.ImagesList){
			    Dlg.ImagesList.refresh();
			  }
            }else{

			  if (storeFiles)
                storeFiles.reload();

			  if (Dlg.storeFiles)
                Dlg.storeFiles.reload();
              if (Dlg.FilesList)
                Dlg.FilesList.refresh();
            }
            Ext.Msg.alert('Success', data.messages);
            FileUploadWin.close();
          }
        }
      );
    }

    FileUploadWin = new Ext.Window({
   		title: 'Upload New File',
      width: 520,
      height: 150,
      draggable: true,
      plain: true,
      modal: true,
      resizable: false,
      bodyBorder: false,
      border: false,
      items: [FileUploadForm],
      buttons:[
     	  {text: 'Upload File',
		     handler: function(){

           	var form = FileUploadForm.getForm();

            if (form.isValid()){

		      Ext.Ajax.request({
			    url: AUrl,
		   	    params: {
                    action: 'check_upload_files',
                    user_id: UserId,
                    type: AFileType,
                    offer_id: AIpId,
                    offer_type: AOfferType,
                    filename: form.findField('file_upload').getValue()
                  },
	   	        success: function(response, request){
                  var data = Ext.decode(response.responseText);
                  var go = true;
                  if (data.res == 'exists'){
					go = false;
                    Ext.MessageBox.confirm('Warning',
					  form.findField('file_upload').getValue()
					  + ' already exists. Do you want to replace it?',
					  function(btn){
			            if ('yes' == btn){
						  go = true;
						  replace = true;
						  funcUpload(true);
			            }
			          }
			        );
                  }else{
                    funcUpload(false);
                  }
                },
	   	        scope: ADlg
	          });

            }  //  if (form.isValid())
          },
		  scope: this
		  }
        ],
        buttonAlign: 'center'
	  });

	FileUploadWin.show();
}
//==============================================================================
// Window and Form for image library

var ImageManagerForm = {
    storeImages: null,
    fmDataView: null,
    tpl: null,
    actionForm: null,
    uploadForm: null,
    browseManager: null,
    offerId: 0,
    offerType: 0,
    imageStore: null,
    parentForm: null,

    _onActionComplete: function(form, action){
      this.fmDataView.store.reload();//.refresh();
      Ext.MessageBox.alert('Info', action.result.messages);
    },

    funcUpload: function(AReplace){
      var form = this.uploadForm.getForm();
	  var replace;
	  if (AReplace)
        replace = 1;
      else
        replace = 0;

      form.submit(
        {
          params: {
            action: 'upload_files',
            user_id: UserId,
            type: 'img',
            offer_type: this.offerType,
            offer_id: this.offerId,
            replace: replace
          },
          waitMsg: 'Uploading your file...',
          failure: function(frm, act){
            var data = Ext.decode(act.response.responseText);
            Ext.Msg.alert('Failure', data.messages);
          },
          success: function(frm, act){
            var data = Ext.decode(act.response.responseText);
/*
            if (ImageManagerForm.parentForm.storeImages)
		        ImageManagerForm.parentForm.storeImages.reload();
*/
            ImageManagerForm.storeImages.reload();

            Ext.Msg.alert('Success', data.messages);
          }
        }
      );
    },

    uploadFiles: function(){

        var form = this.uploadForm.getForm();
        if (form.isValid()){

		      Ext.Ajax.request({
			    url: '../includes/file_action.php',
		   	    params: {
                    action: 'check_upload_files',
                    user_id: UserId,
                    type: 'img',
                    offer_id: this.offerId,
                    offer_type: this.offerType,
                    filename: form.findField('file_upload').getValue()
                  },
	   	        success: function(response, request){
                  var data = Ext.decode(response.responseText);
                  var go = true;
                  if (data.res == 'exists'){
					go = false;
                    Ext.MessageBox.confirm('Warning',
					  form.findField('file_upload').getValue()
					  + ' already exists. Do you want to replace it?',
					  function(btn){
			            if ('yes' == btn){
						  go = true;
						  replace = true;
						  ImageManagerForm.funcUpload(true);
			            }
			          }
			        );
                  }else{
                    ImageManagerForm.funcUpload(false);
                  }
                },
	   	        scope: this
	          });
        }
    },

    selectPicture: function(src, id, name){

	    this.actionForm.findById('image_name').setValue(name);
        this.actionForm.findById('image_name_hid').setValue(src);

	    btns = this.actionForm.buttons;
	    btns[0].enable();
	    btns[1].enable();
    },

    deleteImage: function(){

      var v = ImageManagerForm.actionForm.findById('image_name').getValue();
      if (v != ''){
		Ext.Msg.show({
           title:'Delete',
           msg: 'Are you sure you want to delete?',
           buttons: Ext.Msg.OKCANCEL,
           fn: function(btn){
               if (btn == 'ok') {
			      Ext.Ajax.request({
			        url: '../includes/file_action.php',
			        params: {
			          action: 'delete_file_name',
			          offer_type: ImageManagerForm.offerType,
			          offer_id: ImageManagerForm.offerId,
			          file_name: v
			        },
			        success: function(AResponse){
			          ImageManagerForm.actionForm.findById('image_name').setValue('');
			          ImageManagerForm.actionForm.findById('image_name_hid').setValue('');
/*
			          if (ImageManagerForm.parentForm.storeImages)
			              ImageManagerForm.parentForm.storeImages.load();
*/
			          ImageManagerForm.storeImages.load();

			          Ext.MessageBox.alert('Delete', 'Image has been deleted!');

			        },
			        scope: ImageManagerForm
			      });

      			}
      		}
      	})
      }
    },

    setImage: function(){
	    var id = 'main_image';

	    var v = this.actionForm.findById('image_name_hid').getValue();
		//alert(1);
		if (v != ''){
	      //alert(2);
		  Ext.getDom(id).src = v;
	      var field_id = id + '_hid';

	      this.parentForm.formPanel.getForm().setValues({field_id: v});
	      if (Ext.getCmp(field_id)) {
	      	Ext.getCmp(field_id).setValue(v);
	      }
	      if (Ext.getCmp('main_image_hid')) {
		  	Ext.getCmp('main_image_hid').setValue(v);
		  }
	      this.browseManager.close();
	    }
    },


    showImageManager: function(AItemType, AItemId, AParentForm){

        this.offerId = AItemId;
        this.offerType = AItemType;
        this.parentForm = AParentForm;

        this.tpl = new Ext.XTemplate('<tpl for="." >' +
                                '<div style="float: left; width: 100px; height: 100px; padding: 2px; cursor: pointer;" class="thumb">' +
                                '<a href="#" onclick="ImageManagerForm.selectPicture(\'{url}\', {id}, \'{name}\'); return false;"><img src="{url}" id="img_{id}" width="100" height="100" /></a>' +
                                '</div>' +
                                '</tpl>'
         );

    this.storeImages = new Ext.data.JsonStore({
        method: 'post',
        url: '../includes/file_action.php',
        root: 'images',
        baseParams: {
            action: 'get_images_list',
            user_id: UserId,
            offer_id: this.offerId,
            offer_type: this.offerType
        },
        fields: [
            'id',
            'name',
            'shortName',
            'url',
            'file',
            'caption',
            {name:'size', type: 'float'}
        ]
    });


    this.fmDataView = new Ext.DataView({
      id: 'itemDataView',
      itemSelector: 'div.thumb',
//      store: this.parentForm.storeImages,
      store: this.storeImages,
      height: 310,
      width: 417,
      tpl: this.tpl,
      emptyText: 'No information to display'
    });

    this.actionForm = new Ext.FormPanel({
      url: '../includes/file_action.php',
      defaultType: 'textfield',
      labelWidth: 100,
      frame: true,
      fileUpload: true,
      style: 'padding-bottom: 5px; ',
//      enctype:'multipart/form-data',
      title: '',
      items: [
          {xtype: 'textfield', fieldLabel: 'File Name', name:'image_name',
          id: 'image_name', allowBlank: true,
          readOnly: true, anchor: '100%'},
          {xtype: 'hidden',
             name: 'image_name_hid', id: 'image_name_hid', allowBlank: true, anchor: '100%'}
      ],
	    buttons: [{
			text: 'Select',
			id: 'btn_select_image',
	        disabled: true,
			handler: this.setImage,
            scope: this
		  },
		  {
			text: 'Delete Image',
			id: 'btn_delete_image',
			disabled: true,
			handler: this.deleteImage,
			scope: this
		}
      ]
    });

    this.uploadForm = new Ext.FormPanel({
      url: '../includes/file_action.php',
      defaultType: 'textfield',
      labelWidth: 80,
      width: 448,
      frame: true,
      fileUpload: true,
      enctype:'multipart/form-data',
      title: 'Upload New File (.gif, .jpg, .png, .bmp)',
      items: [
        {xtype: 'panel', layout:'column',
		  width: 420,
          items: [{
            columnWidth:.8,
            labelWidth: 60,
            layout: 'form',
            items: [
               {xtype: 'textfield', inputType: 'hidden', name:'dir',
			       allowBlank: true, value: ''},
		       {xtype: 'textfield', inputType: 'file', fieldLabel: 'Image',
		           name: 'file_upload', allowBlank: true,
		           width: 200
//	        	   anchor: '98%'
		       }
		    ]
		  },
		  {
            columnWidth:.2,
            layout: 'form',
            items: [
                {xtype: 'button', text: 'Upload File',
				    handler: this.uploadFiles, scope: this}
//       	{xtype: 'hidden', name: 'action', value: 'upload_images'}
			]
		  }
		  ]
		}
      ]
    });
    this.uploadForm.on('actioncomplete', this._onActionComplete, this);

    this.browseManager = new Ext.Window({
      title: 'Image Library',
      width: 460,
//      height: 520,
      y: 10,
      closable: true,
      draggable: true,
      plain:true,
      modal: true,
      resizable: false,
      bodyBorder: false,
      border: false,
      items: [
        new Ext.Panel({
          height: 320,
          frame: true,
          autoScroll: true,
          style: 'padding-bottom: 5px; ',
          items: [
            this.fmDataView
          ]
        }),
        this.actionForm,
        this.uploadForm
      ],
      buttons: [{
			text: 'Close',
			handler: function(){
                ImageManagerForm.browseManager.close();
			},
            scope: this
		  }
	   ],
	   buttonAlign: 'right'
    });

    this.browseManager.show();
/*
    if (this.parentForm.storeImages)
        this.parentForm.storeImages.load();
*/
      this.storeImages.load();

        //alert(1);
//    }
  }
}
//===========================================================================
