/* Modifications to this file need to be implemented in the same way
   in the sprocket_searchpanels.js. */

// dependencies: portal/scripts/general.js
var SPI = {
  // domain names
  'domain': {
     'portal': 'http://www.thomson.co.uk',
     'beach': 'http://www.thomsonbeach.co.uk',
     'cruise': 'http://www.thomson.co.uk/cruise.html',
     'dp': 'http://www.thomson.co.uk',
     'ao': 'http://www.thomson.co.uk',
     'flight': 'http://www.thomsonfly.com',
     'ski': 'http://www.thomson-ski.co.uk',
     'worldwide': 'http://www.thomsonworldwide.co.uk',
     'lakes': 'http://www.thomsonlakesandmountains.co.uk',
     'city': 'http://www.thomson.co.uk/buildyourown/search.do?product=citybreaks',
     'villa': 'http://www.thomson.co.uk'
  },
  // product types
  'productTypes': [
    ['sun', 'Sun Holidays'],
    ['cruise', 'Cruise'],
    ['flight', 'Flights'],
    ['accom', 'Hotels'],
    ['ski', 'Ski &amp; Snowboarding'],
    ['city', 'City Breaks'],
    ['villa', 'Villas'],
    ['worldwide', 'Worldwide'],
    ['lakes', 'Lakes &amp; Mountains']
  ],
  // product sub-types
  'radios': {
 'sun': [['package'], ['flight_accom', 'accom', 'flight']],
    'villa': [['package'],['accom','flight']],
    'accom': [[], ['sun', 'city', 'accom']]
  },
  'titles': {
    'default': "I'm looking for..."
  },
  // product sub-type labels
  'labels': {
  'sun': {
        'package': 'Package Holidays',
        'flight_accom': 'Flight + Hotel',
        'accom': 'Hotels',
        'flight': 'Flights'
     },
    'villa': {
      'package': 'Package Holidays',
      'flight_accom': 'Flight + Villa',
      'accom': 'Villas',
      'flight': 'Flights'
    },
    'accom': {
      'sun': 'Sun Hotels + Apartments',
      'city': 'City Hotels',
      'accom': 'Villas'
    }
  }
};

// search panel URLs
SPI.panels = {
  'sun': SPI.domain.beach + '/th/beach/sunSearchPanel.do?promotion=portal-home',
  'villa': SPI.domain.beach + '/th/beach/villaSearchPanel.do?promotion=villa-home',
  'cruise': SPI.domain.cruise,
  'accom': SPI.domain.ao + '/thomson/page/ao/search/searchpanel.page?siteId=SUN&promotion=ao-portal-home'
};
SPI.panels['sun/package'] = SPI.panels.sun;
//SPI.panels['sun/flight_accom'] = SPI.domain.ao + '/holidays.html';
SPI.panels['sun/accom'] = SPI.domain.ao + '/thomson/page/ao/search/searchpanel.page?siteId=SUN';
SPI.panels['villa/package'] = SPI.panels.villa;
//SPI.panels['villa/flight_accom'] = SPI.domain.dp + '/buildyourown/searchPanel.do';
SPI.panels['villa/accom'] = SPI.domain.ao + '/thomson/page/ao/search/searchpanel.page?siteId=TVP';

// product home-page URLs
SPI.home = {
  'sun': SPI.domain.beach + '/th/beach/sunHome.do',
  'cruise': SPI.domain.cruise,
  'villa': SPI.domain.beach + '/th/beach/villaHome.do',
  'accom': SPI.domain.ao + '/thomson/page/ao/home/home.page',
  'flight': SPI.domain.flight,
  'ski': SPI.domain.ski,
  'lakes': SPI.domain.lakes,
  'worldwide': SPI.domain.worldwide,
  'city': SPI.domain.city
};
SPI.home['sun/package'] = SPI.home['sun'];
SPI.home['sun/accom'] = SPI.domain.ao + '/thomson/page/ao/home/home.page';
SPI.home['sun/flight'] = SPI.domain.flight;
//SPI.home['sun/flight_accom'] = SPI.domain.ao + '/holidays.html';
SPI.home['sun/flight_accom'] = 'http://www.thomson.co.uk/holidays.html';
SPI.home['villa/package'] = SPI.home['villa'];
SPI.home['villa/flight_accom'] = SPI.domain.dp + '/buildyourown/search.do?productDisplayed=villas';
SPI.home['villa/accom'] = SPI.domain.ao + '/thomson/page/ao/home/home.page';
SPI.home['villa/flight'] = SPI.domain.flight;

// parse query-string into object
// SPI.params.portal == 'true' if we're on a portal page
// SPI.params.type - holds the holiday-type to be selected onload
// SPI.params.subtype - holds the radio-button to be selected onload
SPI.params = (function() {
  var o = {};
  var query = document.location.search.replace(/^\?/, '');
  if (query) {
    var pairs = query.split('&');
    for (var i = 0; i < pairs.length; i++) {
      var pair = pairs[i].split('=');
      var name = unescape(pair[0]);
      var value = pair.length == 1 ? '' : unescape(pair[1]);
      if (typeof o[name] == 'undefined') {
        o[name] = value;
      } else if (o[name] instanceof Array) {
        o[name].push(value);
      } else {
        o[name] = [o[name], value];
      }
    }
  }
  // merge/replace with existing SPI parameters
  if (window.spiMap) {
    for (var key in spiMap) {
      if (key != 'portal' || !o['portal']) {
        o[key] = spiMap[key];
      }
    }
  }
  return o;
})();

/** Add SPI parameters to URL */
SPI.addParameters = function(url, type, subtype) {
 // Step 1: check url for trailing slash, and any existing query-string -
 // removing any trailing ? or &
 // https://.length == 8
 url = url.replace(/[?&]+$/, '');
 url += (url.indexOf('/', 8) < 0) ? '/?' :
   (url.indexOf('?') < 0) ? '?' : '&';
 var parameters = [];
 // Step 2: Add portal, type and sub-type parameters
 parameters.push('portal=' + (SPI.params.portal == 'true'));
 if (type) parameters.push('type=' + type);
 if (subtype) parameters.push('subtype=' + subtype);
 var values = (window.buildParameters && buildParameters()) || {};
 var standard = {};
 for (var property in values) {
   if (!standard[property]) {
     parameters.push(property + '=' + String(values[property]));
   }
 }
 // added the code for appending the ito and ico code to the query string when the
 // flights or hotels or flights + hotels are selected from seach panel thro radio buttons

 if (subtype == "flight")
 {
   parameters.push("ito=1661");
 }
 else if (subtype == "accom" && SPI.params.portal == 'true')
 {
   parameters.push("ico=PO_Sch_Htl_Rad");
 }
 else if (subtype == "accom" && SPI.params.portal == 'false')
 {
   parameters.push("ito=1576");
 }
 else if (subtype == "flight_accom" && SPI.params.portal == 'false')
 {
    parameters.push("ito=1493");
 }
 else if (subtype == "flight_accom" && SPI.params.portal == 'true')
 {
    parameters.push("ico=PO_Sch_FH_Rad")
 }
 return url + parameters.join('&');
};

/** Called onchange of holiday-type drop-down */
SPI.changeType = function(event, select) {
  var swappable = (window.top != window.self && (SPI.params.portal != 'false'));
  var type = select.value;
  if (type == 'lakes' || type == 'ski') {
    select.selectedIndex = SPI.previouslySelected;
    window.open(SPI.home[type]);
  } else if (swappable && SPI.panels[type]) {
    document.location = SPI.addParameters(SPI.panels[type], type);
  } else {
    select.selectedIndex = SPI.previouslySelected;
    top.location = SPI.addParameters(SPI.home[type], type);
  }
};

/** Called onclick of holiday sub-type radio button */
SPI.changeSubType = function(radio) {
  var type = radio.form.type.value;
  var subtype = radio.value;
  if (SPI.params.subtype == subtype) {
    return;
  }

  if (window.handleHolidayType && window.handleHolidayType(type, subtype)) {
    // update SPI.params to ensure we call handleHolidayType when needed again.
    SPI.params.subtype = subtype;
    return;
  }
  var swappable = (window.top != window.self && (SPI.params.portal != 'false'));
  var type = SPI.params.type;

  var target = null;
  var url = null;
  var specific = type + '/' + subtype;
  if (swappable && SPI.panels[specific]) {
    target = document;
    url = SPI.panels[specific];
  } else if (SPI.home[specific]) {
    target = top;
    url = SPI.home[specific];
  }

  if (target && url) {
    target.location = SPI.addParameters(url, type, subtype);
  } else if (url) {
    window.open(url);
  } else {
    // do nothing
  }
};


/* Write out holiday type drop-down and sub-type radio buttons */
SPI.addProductTypes = function() {
 var type = SPI.params.type || 'sun';
 var html = [];
 html.push('<h2>' + (SPI.titles[type] || SPI.titles['default']) + '</h2>');
 html.push('<select onchange="SPI.changeType(event, this)" name="type" class="type" tabindex="1" id="type">');
 for (var i = 0; i < SPI.productTypes.length; i++) {
   var option = SPI.productTypes[i];
   var label = option[1];
   var value = option[0];
   var selected = (value == type) ? ' selected="selected"' : '';
   if (selected) {
     SPI.previouslySelected = i;
     addOnload(function() { $('type').selectedIndex = SPI.previouslySelected });
   }
   html.push('<option value="' + value + '"' + selected + '>' + label + '</option>');
 }
 html.push('</select>');
 var radios = SPI.radios[type];
 if (radios && radios.length) {
  html.push('<fieldset class="subTypes">');
  var cluster = radios[0];
  var subtype = SPI.params.subtype || 'package';
  for (var i = 0; cluster && i < cluster.length; i++) {
   var value = cluster[i];
   var id = 'radio_' + value;
   var checked = (value == subtype) ? ' checked="checked"' : '';
   html.push('<label for="' + id + '" class="' + value + '"><input type="radio" name="subtype" id="' + id + '" value="' + value + '" onclick="SPI.changeSubType(this)"' + checked + '/>' + SPI.labels[type][value] + '</label>');
  }
  if (radios.length > 1) {
   var prefix = (radios[0] && radios[0].length) ? 'Or ' : '';
   html.push('<p>' + prefix + 'Build Your Own Holiday</p>');
   cluster = radios[1];
   for (var i = 0; cluster && i < cluster.length; i++) {
     var value = cluster[i];
     var id = 'radio_' + value;
     var checked = (value == subtype) ? ' checked="checked"' : '';
     html.push('<label for="' + id + '" class="' + value + '"><input type="radio" name="subtype" id="' + id + '" value="' + value + '" onclick="SPI.changeSubType(this)"' + checked + '/>' + SPI.labels[type][value] + '</label>');
   }
  }
  html.push('</fieldset>');
  html.push('<input type="hidden" name="portal" value="' + (SPI.params.portal == 'true') + '"/>');
 }
 html.push('<input type="hidden" name="portal" value="' + (SPI.params.portal == 'true') + '"/>');
 document.write(html.join('\r\n'));
};

SPI.showTeasers = function() {
 if (!$('promos') && SPI.params.promotion) {
   var promosURL = SPI.domain.beach + '/th/common/include/promos.jsp?promotion=' + SPI.params.promotion;
   var body = document.body;
   if (!body.insertAdjacentHTML) {
     // standards
     var iframe = document.createElement('iframe');
     iframe.setAttribute('src', promosURL);
     iframe.setAttribute('frameborder', '0');
     iframe.setAttribute('scrolling', 'no');
     iframe.setAttribute('id', 'promos');
     iframe.setAttribute('width', '225px');
     body.appendChild(iframe);
   } else {
     var html = '<iframe src="' + promosURL + '" style="width:209px;" frameborder="0" scrolling="0" id="promos"></iframe>';
     body.insertAdjacentHTML('beforeEnd', html);
   }
 }
};

// Write out HTML for product-type drop-down and sub-type radio buttons
SPI.addProductTypes();

// Add Teasers/Promo <iframe> after panel finishes loading.
if (window.top != window.self) { addOnload(SPI.showTeasers) }

