/**
 * This is the Traffics form base class
 * @author Michael Hatzfeld <m.hatzfeld@datanet21.de>
 *
 * @constructor
 * @param {string} name name of the form
 * @param {string} engine searchType (pauschal, hotelonly, flight, etc.)
 * @param {string} url url to the booking/search engine
 */
function TRAFFICS(formId,engine,url,objName)
{
  /**
   * Name of the form (default: trf1)
   * @type {string}
   */
  this.formId  = typeof(formId)!='undefined'?formId:"trf1";

  /**
   * Name of the searchType (default: pauschal)
   * @type {string}
   */
  this.engine  = typeof(engine)!='undefined'?engine:"pauschal";

  /**
   * Url for the booking/search engine
   * @type {string}
   */
  this.url     = typeof(url)!='undefined'?url:"http://www.deutschereise.de/angebote";

  /**
   * Object varname for calling delay method
   * @type {string}
   */
  this.objName = typeof(objName)!='undefined'?objName:"IBE";

  /**
   * Subtype (all, lastminute)
   * @type {string}
   */
  this.sub = typeof(sub)!='undefined'?sub:"all";

  // Change form action to the given url
  $('#' + formId).attr('action', this.url);

  // Standard dropdown values/pref.
  // format: 'css-id' : 'js-var-name;add-default-option;selected-option'
  this.dropdowns = {
   'priceMax'         : 'maxPrices',
   'persons'          : 'persons;false;2',
   'child1'           : 'childrenAge;false',
   'child2'           : 'childrenAge;false',
   'child3'           : 'childrenAge;false',
   'hotelStc'         : 'hotelStc;false',
   'dateRange'        : 'dateRanges;false',
   'hotelVpc'         : 'hotelVpc;false',
   'hotelZac'         : 'hotelZac;false',
   'departureAirport' : 'departureAirportsTravel',
   'operator'         : 'operatorsFlight'
  };

  //this.path2js = 'fileadmin/templates/dr/js/traffics/';
  this.path2js = 'angebote/js/import/';

  this.jsFiles = [
    this.path2js + 'regions_pauschal.js',
    this.path2js + 'js_choices.js',
    this.path2js + 'op.js'
  ];
  
  if(this.engine == "flight")
  {
    this.jsFiles.push(this.path2js + 'dip.js')    
  }

  if(this.engine == "hotelonly")
  {
    this.jsFiles.push(this.path2js + 'regions_hotel.js')    
  }
  else
  {
     this.jsFiles.push(this.path2js + 'regions_pauschal.js')   
  }

  this.selector_region   = '#' + this.formId + ' select[name="region"]';
  this.selector_operator = '#' + this.formId + ' select[name="operator"]';
  this.selector_area     = '#' + this.formId + ' select[name="area"]';
}


TRAFFICS.prototype = {
  /**
   * Adding attributes
   */
  extend: function(dest,src){
    for(attr in src) dest[attr]=src[attr];
    return dest;
  },

  /**
   * Adding files dynamical to the html-tree
   */
  include: function(tag,pfad){
    var attrs = {
      link:   {rel:"stylesheet",type:"text/css",href:pfad},
      script: {type:"text/javascript",src:pfad}
    };
    document.getElementsByTagName("head")[0].appendChild(
      this.extend(document.createElement(tag),attrs[tag])
    );
  },

  /**
   * Adds js files to the document
   */
  includeFiles: function()
  {
    for(var i=0;i<this.jsFiles.length;++i) this.include("script",this.jsFiles[i]);
  },

  /**
   * Writes hidden fields to the given form (from hiddenFieldArray)
   */
  writeHiddenFields: function(){
    obj = this;
    $.each(this.hiddenFields, function(key, value){
      obj.renderHiddenField(key, value);
    });
  },

  /**
   * Renders a hidden field, by the given values
   */
  renderHiddenField: function(name, value){
     $('#'+ this.formId).prepend('<input type="hidden" name="'+name+'" value="'+value+'">'+"\n");
  },

  /**
   * Adds js files to the document
   */
  initAll: function()
  {
    this.initGeneralFields();

  if(this.engine == "flight")
  {
    this.initFlightDestinationFields();
  }
  else
  {
    this.initDestinationFields();
  }

    // Renders two mandatory hiddenfields within the form
    this.renderHiddenField('searchTyp', this.engine);
    this.renderHiddenField('sub', this.sub);
  },

  /**
   * Checks if the needed form vars (Dropdown-Field values)
   * are successsfull loaded and runs the loadFormFields method
   */
  initGeneralFields: function(){

    var dropdownVar;

    for(var i in this.dropdowns){
      dropdownVar = this.dropdowns[i].split(";");

      // check if vars from dropdown array exists
      // (If yes, they are successfully from the
      // external js files included and parsed)
      if(typeof(window[dropdownVar[0]])=='undefined'){
        window.setTimeout(this.objName + ".initGeneralFields()",20);
        return;
      }
      
      this.addDepartureSelectFlags();
    }

    this.loadFormFields();
  },

  /**
   * Loads and process the data for the dropdown fields
   * and calls the fillDropDown method
   */
  addDepartureSelectFlags: function(){
    $(".departureAirport option[value*=',']").addClass('optcat');
    $('.departureAirport option[value=BRE,HAJ,HAM,KEL,LBC,RLG,]').attr('style', 'background-position: 0px -12px');
    $('.departureAirport option[value=FRA,KSF,SCN,ZQW,]').attr('style', 'background-position: 0px -12px');
    $('.departureAirport option[value=BER,DRS,ERF,LEJ,SXF,TXL,]').attr('style', 'background-position: 0px -12px');
    $('.departureAirport option[value=FDH,FKB,FMM,MUC,NUE,STR,]').attr('style', 'background-position: 0px -12px');
    $('.departureAirport option[value=CGN,DTM,DUS,FMO,MST,NRN,PAD,]').attr('style', 'background-position: 0px -12px');
    $('.departureAirport option[value=SXB,]').attr('style', 'background-position: 0px -26px');
    $('.departureAirport option[value=LUX,]').attr('style', 'background-position: 0px -96px');
    $('.departureAirport option[value=AMS,EIN,GRQ,RTM,]').attr('style', 'background-position: 0px -54px');
    $('.departureAirport option[value=BZG,GDN,KRK,KTW,LCJ,POZ,WAW,WRO,]').attr('style', 'background-position: 0px -68px');
    $('.departureAirport option[value=BRN,BSL,GVA,ZRH,]').attr('style', 'background-position: 0px -40px');
    $('.departureAirport option[value=PRG,]').attr('style', 'background-position: 0px -82px');
    $('.departureAirport option[value=GRZ,INN,KLU,LNZ,SZG,VIE,]').attr('style', 'background-position: 0px -110px');
    $('.departureAirport option[value=BRW,LGG,]').attr('style', 'background-position: 0px 0px'); 
  },
  
  /**
   * Loads and process the data for the dropdown fields
   * and calls the fillDropDown method
   */
  loadFormFields: function(){

    var obj = this;
    var defaultOpt, selected;
    $.each(this.dropdowns, function(key, value)
    {
      defaultOpt = true;
      selected = '';

      dropdownVar = value.split(";");

      // Check if there should be no default option.
      if(typeof(dropdownVar[1]) != 'undefined')
      {
        defaultOpt = dropdownVar[1];
      }

      // Check for a selected item
      if(typeof(dropdownVar[2]) != 'undefined')
      {
        selected = dropdownVar[2];
      }

      // calling dropdown setter function
      obj.fillDropdown(key, window[dropdownVar[0]], defaultOpt, selected);

    });
  },

  /**
   * Adds the option elements to a Select (Dropdown)
   * form field
   */
  fillDropdown: function(name, content, defaultOpt, selected){

    var selector = '#' + this.formId + ' select[name="' + name + '"]';

    $(selector).empty();

    // add empty element
    if(defaultOpt == true)
    {
      $(selector).append('<option value="">- beliebig -</option>');
    }

    var obj = this;

    $.each(content, function(key, value)
    {
      if(key == selected)
      {
        $(selector).append('<option value="' + key + '" selected="selected">' + value + '</option>');
      }
      else
      {
        $(selector).append('<option value="' + key + '">' + value + '</option>');
      }
    });
  },

  //
  // DEFUALT PAUSCHAL DROPDOWN
  //

  initDestinationFields: function()
  {
    if(typeof(window['regions'])=='undefined'              ||
       typeof(window['operatorDestinations'])=='undefined'
       ){

      window.setTimeout(this.objName + ".initDestinationFields()", 20);
      return;
    }

    obj = this;
    // move this line to the render function of the form widget later. //2011-03-22 JR: Why?
    $(this.selector_region).change(function(){
      obj.changeRegion();
    });

    $(this.selector_operator).change(function(){
      obj.changeOperatorDestination();
    });

    this.changeOperatorDestination();
  },


  /**
  * Init "region" dropdown with all values of variable "regions" in regions.js
  * Toggles changen()
  *
  * @param val - Value to which is selected by default
  */
  initRegion: function(val)
  {
    $(this.selector_region).empty();

    // add empty element
    $(this.selector_region).append('<option value="">- beliebig -</option>');

    for(v in regions)
    {
      $(this.selector_region).append('<option value="' + v + '">' + regions[v].name + '</option>');
    }

    if(val)
    {
      $(this.selector_region).val(val);
    }

    $(this.selector_region).change();
  },


  /**
  * Changes "region" dropdown depending on selection in "operator" dropdown
  * If no destinations for an operator provided, all destinations will be used
  *
  * Uses "operatorDestinations" variable in od.js
  */
  changeOperatorDestination: function()
  {
    var operatorId = $(this.selector_operator).val();
    var regionVal  = $(this.selector_region).val();

    if(operatorId == '' || operatorId == null)
    {
      this.initRegion(regionVal);
      return;
    }

    var od = operatorDestinations[operatorId];

    if (od.length <= 0)
    {
      this.initRegion(regionVal);
      return;
    }

    $(this.selector_region).empty();
    $(this.selector_region).append('<option value="">- beliebig -</option>');

    for(v in od)
    {
      if(regions[od[v]])
      {
        $(this.selector_region).append('<option value="' + od[v] + '">' + regions[od[v]].name + '</option>');

        if (regionVal == od[v])
        {
          $(this.selector_region).val(od[v]);
        }
      }
    }

    $(this.selector_region).change();
  },

  /**
  * If region is changed, fill new values into area
  * Keeps value of area selected, if it is available in new values
  */
  changeRegion: function()
  {
    var value     = $(this.selector_region).val();
    var areaValue = $(this.selector_area).val();

    $(this.selector_area).empty();
    $(this.selector_area).append('<option value="">- beliebig -</option>');

    if(value == '')
    {
      return;
    }

    for(v in regions[value].regions)
    {
      $(this.selector_area).append('<option value="' + v + '">' + regions[value].regions[v] + '</option>');

      if (areaValue == v)
      {
        $(this.selector_area).val(v);
      }
    }
  },

  //
  // FLIGHT DESTINATION FUNCTIONS
  //

  initFlightDestinationFields: function(region, area)
  {
    if(typeof(window['destinationAirports'])=='undefined'              ||
       typeof(window['operatorDestinationsFlight'])=='undefined'
       ){

      window.setTimeout(this.objName + ".initFlightDestinationFields()", 20);
      return;
    }

    obj = this;
    $(this.selector_region).change(function(){
      obj.changeFlightRegion();
    });

    $(this.selector_operator).change(function(){
      obj.changeFlightOperatorDestination();
    });

    this.changeFlightOperatorDestination();

    //if only area is provided, try to find it in current region list and get the first value
    if(region == '' && area != '')
    {
      //cycle through all options of region element
      $(this.selector_region + ' option').each(function(i, option) {

        //if element contains current area
        if($(option).val().search(area) != -1)
        {
          region = $(option).val();
          return;
        }
      });
    }

    //init with values from request
    //$(this.selector_region).val(region).change();
    //$(this.selector_area).val(area);
  },


  /**
   * Init "region" dropdown with all values of variable "destinationAirports" in dip.js
   * Toggles change()
   *
   * @param val - Value to which is selected by default
   */
  initFlightRegion: function (val)
  {
    $(this.selector_region).empty();

    // add empty element
    $(this.selector_region).append('<option value="">- beliebig -</option>');

    for(v in destinationAirports)
    {
      $(this.selector_region).append('<option value="' + v + '">' + destinationAirports[v].name + '</option>');
    }

    if(val)
    {
      $(this.selector_region).val(val);
    }

    $(this.selector_region).change();
  },


  /**
   * Changes "region" dropdown depending on selection in "operator" dropdown
   * If no destinations for an operator provided, all destinations will be used
   *
   * Uses "operatorDestinationsFlight" variable in od.js
   */
  changeFlightOperatorDestination: function()
  {
    var operatorId = $(this.selector_operator).val();
    var regionVal  = $(this.selector_region).val();

    if(operatorId == '' || operatorId == null)
    {
      this.initFlightRegion(regionVal);
      return;
    }

    var od = operatorDestinationsFlight[operatorId];

    if (od.length <= 0)
    {
      this.initFlightRegion(regionVal);
      return;
    }


    $(this.selector_region).empty();
    $(this.selector_region).append('<option value="">- beliebig -</option>');

    var airports;
    for(v in od)
    {
      //split to array
      airports = od[v].split(',');

      //find airports-"key"
      for(region in destinationAirports)
      {
        //if a region is found, add element to dropdown.
        if (region.search(airports[0]) != -1)
        {
          $(this.selector_region).append('<option value="' + region + '">' + destinationAirports[region].name + '</option>');

          //if region matches old dropdown, select it
          if (regionVal == region)
          {
            $(this.selector_region).val(region);
          }
        }
      }
    }

    $(this.selector_region).change();
  },


  changeFlightRegion: function()
  {
    //get value from region dropdown
    var value       = $(this.selector_region).val();
    var areaValue   = $(this.selector_area).val();

    $(this.selector_area).empty();
    $(this.selector_area).append('<option value="">- beliebig -</option>');

    if(value == '' || value == 'undefined')
    {
      return;
    }

    //if isset operator dropdown, get its value and match it with array
    if($(this.selector_operator).val() != '')
    {
      var od = operatorDestinationsFlight[$(this.selector_operator).val()];

      //all regions of operator
      for(region in od)
      {
        //all airports for this region
        for(v in destinationAirports[value].regions)
        {
          //check if airport is in operator list
          if(od[region].search(v) != -1)
          {
            $(this.selector_area).append('<option value="' + v + '">' + destinationAirports[value].regions[v] + '</option>');

            if (areaValue == v)
            {
              $(this.selector_area).val(v);
            }
          }
        }
      }
    }
    else
    {
      for(v in destinationAirports[value].regions)
      {
        $(this.selector_area).append('<option value="' + v + '">' + destinationAirports[value].regions[v] + '</option>');

        if (areaValue == v)
        {
          $(this.selector_area).val(v);
        }
      }
    }
  }

}


