#include <WScom.h>
#include <WSCfunctionList.h>
#include <WSCbase.h>
//----------------------------------------------------------
//Function for the event procedure
//----------------------------------------------------------
#include <WSCbaseDialog.h>
#include <WSCvifield.h>
#include <WSCtextField.h>
extern WSCvifield* newvifi_005;
extern WSCtextField* newtext_001;

void activate1(WSCbase* object){
  WSCbaseDialog* dialog = (WSCbaseDialog*)object->cast("WSCbaseDialog");

  WSCstring searchstr,srcstr;
  searchstr = newvifi_005->getProperty(WSNlabelString);
  WSCushort* searchstrUCS2 = WSGFgetUCS2(searchstr,WS_EN_DEFAULT);
  srcstr = newtext_001->getProperty(WSNlabelString);
  WSCushort* srcstrUCS2 = WSGFgetUCS2(srcstr,WS_EN_DEFAULT);
  long cursor = newtext_001->getSelectedPos();
  long slen = WSGFstrlenUCS2(searchstrUCS2);

  if (dialog->getStatus() == WS_DIALOG_OK){ //UPPER SEARCH
    srcstrUCS2[cursor] = 0;
    WSCushort* ptr = srcstrUCS2;
    long len = WSGFstrlenUCS2(ptr);
    long i;
    for(i=0; i<len - slen +1; i++){
      if (!memcmp(&ptr[len-slen-i],searchstrUCS2,slen*sizeof(WSCushort))){
        //hit!
        cursor = len -slen -i;
        newtext_001->setSelect(cursor,slen);
        delete searchstrUCS2;
        delete srcstrUCS2;
        return;
      }
    }
  }else if (dialog->getStatus() == WS_DIALOG_NO){ //NORMAL SEARCH
    WSCushort* ptr = srcstrUCS2;
    long len = WSGFstrlenUCS2(ptr);
    long i;
    for(i=cursor + slen; i<len; i++){
      if (!memcmp(&ptr[i],searchstrUCS2,slen*sizeof(WSCushort))){
        //hit!
        cursor = i;
        newtext_001->setSelect(cursor,slen);
        delete searchstrUCS2;
        delete srcstrUCS2;
        return;
      }
    }
  }
  delete searchstrUCS2;
  delete srcstrUCS2;
}
static WSCfunctionRegister  op("activate1",(void*)activate1);
