/* Loading JQUERY dynamically */
var jquery_src  = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js";
var jsonlib_src = "http://ws.expopromoter.com/com.expopromoter.widget.calendar/json2.js";
var styles_src  = "http://ws.expopromoter.com/com.expopromoter.widget.calendar/styles.css";
document.writeln('<'+'link type="text/css" rel="stylesheet" href="' + styles_src + '" />');
document.writeln('<div id="EPG_CALENDAR_container"></div>');

var EPG_Calendar = {
  
  containerId: null,
  container: null,
  
  settings: {
    accessPoint: "http://ws.expopromoter.com/json/v2/index3.php?callBack=?&callMethod=multiCall&key=P49464a02f0f76&publisher=434&",
    filterVisible: true,
    width:    null,
    height:   null,
    border:   "#666666",
    limit:    10,
    countryOnly:  null,
    categoryOnly: null,
    subCategoryOnly: null,
    encoding: document.characterSet || document.charset || "UTF8",
    language: 'en',
    targetHost: 'expopromoter.com',
    partner: null
  },
  
  messages: {
    en: [
	  'Trade shows',
      'filter',
      '(select category)',
      '(select subcategory)',
      '(select category first)',
      '(select country)',
      '(select city)',
      '(select country first)',
      '(month)',
      'Category',
      'Subcategory',
      'Country',
      'City',
      'Year',
      'Month',
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
      'July',
      'August',
      'September',
      'October',
      'November',
      'December'
    ],
    
    ru: [
	  'Выставки',
      'фильтр',
      '(выберите тематику)',
      '(выберите подтематику)',
      '(сначала выберите тематику)',
      '(выберите страну)',
      '(выберите город)',
      '(сначала выберите страну)',
      '(месяц)',
      'Тематика',
      'Подтематика',
      'Страна',
      'Город',
      'Год',
      'Месяц',
      'Январь',
      'Февраль',
      'Март',
      'Апрель',
      'Май',
      'Июнь',
      'Июль',
      'Август',
      'Сентябрь',
      'Октябрь',
      'Ноябрь',
      'Декабрь'
    ],

    ruWin: [
	   '&#1042;&#1099;&#1089;&#1090;&#1072;&#1074;&#1082;&#1080;',
		'&#1092;&#1080;&#1083;&#1100;&#1090;&#1088;',
      '(&#1074;&#1099;&#1073;&#1077;&#1088;&#1080;&#1090;&#1077; &#1090;&#1077;&#1084;&#1072;&#1090;&#1080;&#1082;&#1091;)',
      '(&#1074;&#1099;&#1073;&#1077;&#1088;&#1080;&#1090;&#1077; &#1087;&#1086;&#1076;&#1090;&#1077;&#1084;&#1072;&#1090;&#1080;&#1082;&#1091;)',
      '(&#1089;&#1085;&#1072;&#1095;&#1072;&#1083;&#1072; &#1074;&#1099;&#1073;&#1077;&#1088;&#1080;&#1090;&#1077; &#1090;&#1077;&#1084;&#1072;&#1090;&#1080;&#1082;&#1091;)',
      '(&#1074;&#1099;&#1073;&#1077;&#1088;&#1080;&#1090;&#1077; &#1089;&#1090;&#1088;&#1072;&#1085;&#1091;)',
      '(&#1074;&#1099;&#1073;&#1077;&#1088;&#1080;&#1090;&#1077; &#1075;&#1086;&#1088;&#1086;&#1076;)',
      '(&#1089;&#1085;&#1072;&#1095;&#1072;&#1083;&#1072; &#1074;&#1099;&#1073;&#1077;&#1088;&#1080;&#1090;&#1077; &#1089;&#1090;&#1088;&#1072;&#1085;&#1091;)',
      '(&#1084;&#1077;&#1089;&#1103;&#1094;)',
      '&#1058;&#1077;&#1084;&#1072;&#1090;&#1080;&#1082;&#1072;',
      '&#1055;&#1086;&#1076;&#1090;&#1077;&#1084;&#1072;&#1090;&#1080;&#1082;&#1072;',
      '&#1057;&#1090;&#1088;&#1072;&#1085;&#1072;',
      '&#1043;&#1086;&#1088;&#1086;&#1076;',
      '&#1043;&#1086;&#1076;',
      '&#1052;&#1077;&#1089;&#1103;&#1094;',
      '&#1071;&#1085;&#1074;&#1072;&#1088;&#1100;',
      '&#1060;&#1077;&#1074;&#1088;&#1072;&#1083;&#1100;',
      '&#1052;&#1072;&#1088;&#1090;',
      '&#1040;&#1087;&#1088;&#1077;&#1083;&#1100;',
      '&#1052;&#1072;&#1081;',
      '&#1048;&#1102;&#1085;&#1100;',
      '&#1048;&#1102;&#1083;&#1100;',
      '&#1040;&#1074;&#1075;&#1091;&#1089;&#1090;',
      '&#1057;&#1077;&#1085;&#1090;&#1103;&#1073;&#1088;&#1100;',
      '&#1054;&#1082;&#1090;&#1103;&#1073;&#1088;&#1100;',
      '&#1053;&#1086;&#1103;&#1073;&#1088;&#1100;',
      '&#1044;&#1077;&#1082;&#1072;&#1073;&#1088;&#1100;'
    ]
  },

  
  /*************************************************************************************************/
  
  load: function() {
    if (typeof $ == "undefined") this.includeScript(jquery_src);
    this.includeScript(jsonlib_src);
    this.tryReady(0);
  },
  
  /*************************************************************************************************/
  
  refresh: function() {
    this.settings = {
      accessPoint: "http://ws.expopromoter.com/json/v2/index3.php?callBack=?&callMethod=multiCall&key=P49464a02f0f76&publisher=434&",
      filterVisible: true,
      width:    null,
      height:   null,
      border:   "#AAA",
      limit:    10,
      countryOnly:  null,
      categoryOnly: null,
      subCategoryOnly:null,
      language: 'en',
      targetHost: 'expopromoter.com'
    }
    
    this.tryReady(0);
  },
  
  /*************************************************************************************************/
  
  includeScript: function(filename) {
    var fileref = document.createElement('script');
    fileref.setAttribute("type","text/javascript");
    fileref.setAttribute("src", filename);
    if (typeof fileref != "undefined") document.getElementsByTagName("head")[0].appendChild(fileref);
  },
  
  /*************************************************************************************************/
  
  tryReady: function(time_elapsed) {
    /* Continually polls for jQuery library. */
    if (typeof $ == "undefined" || typeof JSON == "undefined") {
      if (time_elapsed <= 5000) {
        setTimeout("EPG_Calendar.tryReady(" + (time_elapsed + 200) + ")", 200);
      } else {
        alert("Timed out while loading JS libraries.");
      }
    } else {
      if (typeof EPG_Options == "undefined") {
        this.init();
      } else {
        this.init(EPG_Options);
      }
      this.run();
    }
  },
  
  /*************************************************************************************************/
  
  init: function(options) {
    $.extend(this.settings, options);
    this.containerId = "#EPG_CALENDAR_container";
    this.container = $(this.containerId);
    
    this.setValue('today', new Date());
    this.setValue('yearFrom', this.getValue('today').getFullYear());
    this.setValue('monthFrom', this.getValue('today').getMonth() + 1);
    this.setValue('dayFrom', this.getValue('today').getDate());

/*
    this.setValue('year', null);
    this.setValue('month', null);
    this.setValue('category', null);
    this.setValue('subcategory', null);
    this.setValue('country', null);
    this.setValue('city', null);
*/
  },
  
  /*************************************************************************************************/
  
  getValue: function(s) {
    return this.settings[s];
  },
  
  /*************************************************************************************************/
  
  setValue: function(s, v) {
    this.settings[s] = v;
  },
  
  /*************************************************************************************************/
  
  t: function(s) {
    s = $.trim(s); 
    var lang = this.getValue('language');
    var ix = $.inArray(s, this.messages['en']);
    
    if (ix == -1) {
      return s;
    } else {
      return this.messages[lang][ix];
    }
  },
  
  /*************************************************************************************************/
  
  toggleFilter: function() {
    var filter = $('.EP_filter', this.container);
  
    if (this.getValue('filterVisible')) {
      filter.slideUp();
       $('#EP_trigger_link span').html('&darr;');
      this.setValue('filterVisible', 0);
    } else {
      filter.slideDown();
     
      $('#EP_trigger_link span').html('&uarr;');
      this.setValue('filterVisible', 1);
    }

    return false;
  },
  
  /*************************************************************************************************/
  
  updateView: function() {
    var $this = EPG_Calendar;
    
    var yearS        = $($this.containerId + ' .EP_select_year');
    var monthS       = $($this.containerId + ' .EP_select_month');
    var categoryS    = $($this.containerId + ' .EP_select_category');
    var subcategoryS = $($this.containerId + ' .EP_select_subcategory');
    var countryS     = $($this.containerId + ' .EP_select_country');
    var cityS        = $($this.containerId + ' .EP_select_city');
  
    $this.setValue('year', yearS.val());
    $this.setValue('month', monthS.val());
    $this.setValue('category', $this.getValue('categoryOnly') ? $this.getValue('categoryOnly') : categoryS.val());
    $this.setValue('subcategory', subcategoryS.val());
    $this.setValue('country', $this.getValue('countryOnly') ? $this.getValue('countryOnly') : countryS.val());
    $this.setValue('city', cityS.val());
    
    var country  = $this.getValue('countryOnly') ? $this.getValue('countryOnly') : $this.getValue('country');
    var category = $this.getValue('categoryOnly') ? $this.getValue('categoryOnly') : $this.getValue('category');
    var subcategory = $this.getValue('subCategoryOnly') ? $this.getValue('subCategoryOnly') : $this.getValue('subcategory');
   
    var data = {
      funcs: [
        'getExhibitionCategoriesList', 
        'getExhibitionSubCategoriesList',
        'getLimitedCountriesList', 
        'getLimitedCitiesList',
        'getYearsListFromExhibitionList', 
        'getExhibitionsList'
      ],
      params: [
        [ 200, 1, false ],
        
        [ 200, 1, category ],
        
        [
          'ExhibitionsList', 
          {
            categoryId: category, subCategoryId: subcategory, 
            countryId: country, cityId: $this.getValue('city'), 
            yearFrom: $this.getValue('yearFrom'), monthFrom: $this.getValue('monthFrom'), 
            dayFrom: $this.getValue('dayFrom'), year: $this.getValue('year'), month: $this.getValue('month')
          }
        ],
        
        [
          'ExhibitionsList', 
          {
            categoryId: category, subCategoryId: subcategory, 
            countryId: country, yearFrom: $this.getValue('yearFrom'), 
            monthFrom: $this.getValue('monthFrom'), dayFrom: $this.getValue('dayFrom'), 
            year: $this.getValue('year'), month: $this.getValue('month')
          }
        ],
        
        [
          {
            categoryId: category, subCategoryId: subcategory, 
            countryId: country, cityId: $this.getValue('city'), 
            yearFrom: $this.getValue('yearFrom'), monthFrom: $this.getValue('monthFrom'), 
            dayFrom: $this.getValue('dayFrom'), year: $this.getValue('year')
          }
        ],
        
        [
          $this.getValue('limit'), 1, 
          {
            categoryId: category, subCategoryId: subcategory, 
            countryId: country, cityId: $this.getValue('city'), 
            yearFrom: $this.getValue('yearFrom'), monthFrom: $this.getValue('monthFrom'), 
            dayFrom: $this.getValue('dayFrom'), year: $this.getValue('year'), month: $this.getValue('month')
            
          }
        ]
      ]
    }

    var limit    = $this.getValue('limit');
    var base_url = $this.getValue('accessPoint');
    var lang     = $this.getValue('language');
    var cp       = $this.getValue('encoding');
    
    if (cp != "UTF8" && cp != "UTF-8" && lang == 'ru') {
      $this.setValue('language', 'ruWin');
    }
    if (lang == 'ruWin') {
    	lang = 'ru';
    }
    
    var params = JSON.stringify(data);
   

    var url = base_url + "lang=" + lang + "&cp=" + cp + "&params=" + escape(params) + "&rnd=" + Math.random()*1000000;
    
    $.getJSON(url, $this.render);
    
    return false;
  },
  
  /*************************************************************************************************/
  
  render: function(data) {
    var $this = EPG_Calendar;
    
    // Helper function to build a SELECT from the list
    var buildSelect = function(id, list, value, disabled) {
		//if(disabled){ return '';}
      var selectStr = '<select class="EP_select_'+id+'" id="'+id+'" name="'+id+'"' + 
                      (disabled ? ' disabled="disabled"' : '')+'>'+"\n";
      selectStr += '<option value="">'+$this.t('(select '+id+')')+'</option>'+"\n";

      for (var i = 0, len = list.length; i < len; i++) {
        selectStr += '<option value="'+list[i].id+'" '+(value == list[i].id ? 'selected="selected"' : '')+'>'+
                     list[i].name+'</option>'+"\n";
      }
      selectStr += '</select>' + "\n";

      return selectStr;
    }

    if ($this.getValue('width'))  $this.container.css("width", $this.getValue('width'));
    if ($this.getValue('height')) $this.container.animate({ height : $this.getValue('height') });
    
    var categoriesList = data.getExhibitionCategoriesList.data;
    var subcatList     = data.getExhibitionSubCategoriesList.data;
    var countriesList  = data.getLimitedCountriesList.data;
    var citiesList     = data.getLimitedCitiesList.data;
    var yearsList      = data.getYearsListFromExhibitionList.data;
    var exList         = data.getExhibitionsList.data;
    
    var category       = $this.getValue('category');
    var subcategory    = $this.getValue('subcategory');
    var country        = $this.getValue('country');
    var city           = $this.getValue('city');
    var yearFrom       = $this.getValue('yearFrom');
    var year           = $this.getValue('year');
    var month          = $this.getValue('month');
    var lang           = $this.getValue('language');
    
    if (lang == 'ruWin') {
    	lang = 'ru';
    }
    
    var monthsList = [
      $this.t('(month)'),
      $this.t('January'),
      $this.t('February'),
      $this.t('March'),
      $this.t('April'),
      $this.t('May'),
      $this.t('June'),
      $this.t('July'),
      $this.t('August'),
      $this.t('September'),
      $this.t('October'),
      $this.t('November'),
      $this.t('December'),
    ]
    
    // Построение содержимого информера
    var content = '';

    content += '<div id="EP_trigger"><div id="EP_header">'+$this.t('Trade shows')+'</div><a id="EP_trigger_link" onclick="EPG_Calendar.toggleFilter();">'+$this.t('filter')+' <span>&uarr;</span></a><div class="EP_clr"></div></div>' + "\n";

    var categorySelect    = buildSelect('category',    categoriesList, category,    $this.getValue('categoryOnly'));
    var subcategorySelect = buildSelect('subcategory', subcatList,     subcategory, $this.getValue('subCategoryOnly'));
    var countrySelect     = buildSelect('country',     countriesList,  country,     $this.getValue('countryOnly'));
    var citySelect        = buildSelect('city',        citiesList,     city);

    // START Years list
    var yearSelect = '<select class="EP_select_year" id="year" name="year" style="width:auto;">' + "\n";
    for (var i = 0, len = yearsList.length; i < len; i++) {
      if (yearsList[i] < yearFrom) continue; 
      yearSelect += '<option value="'+yearsList[i]+'" '+(year == yearsList[i] ? 'selected="selected"' : '')+'>'+yearsList[i]+'</option>' + "\n";
    }
    yearSelect += '</select>' + "\n";
    // FINISH Years list

    // START Months list
    var monthSelect = '<select class="EP_select_month" id="month" name="month">' + "\n";
    for (var i = 0; i <= 12; i++) {
      monthSelect += '<option value="'+(i ? i : '')+'" '+(month == i ? 'selected="selected"' : '')+'>'+monthsList[i]+'</option>' + "\n";
    }
    monthSelect += '</select>' + "\n";
    // FINISH Years list

    
    content += '<table class="EP_filter" width="100%"' + (!$this.getValue('filterVisible') ? ' style="display:none"' : '') + '>' + "\n";
    if(!$this.getValue('categoryOnly')){
		content += '<tr valign="top">' + "\n";
		content += '  <td width="20%"><label for="category">'+$this.t('Category')+'</label></td>' + "\n";
		content += '  <td colspan="3">'+categorySelect+'</td>' + "\n";
		content += '</tr>' + "\n";
		content += '' + "\n";
	}
    if(!$this.getValue('subCategoryOnly')){
		content += '<tr valign="top">' + "\n";
		content += '  <td width="20%"><label for="subcategory">'+$this.t('Subcategory')+'</label></td>' + "\n";
		content += '  <td colspan="3">'+subcategorySelect+'</td>' + "\n";
		content += '</tr>' + "\n";
		content += '' + "\n";
	}
    content += '<tr valign="top">' + "\n";
    content += '  <td width="20%"><label for="country">'+$this.t('Country')+'</label></td>' + "\n";
    content += '  <td colspan="3">'+countrySelect+'</td>' + "\n";
    content += '</tr>' + "\n";
    content += '' + "\n";
    
    content += '<tr valign="top">' + "\n";
    content += '  <td width="20%"><label for="city">'+$this.t('City')+'</label></td>' + "\n";
    content += '  <td colspan="3">'+citySelect+'</td>' + "\n";
    content += '</tr>' + "\n";
    content += '' + "\n";
    
    content += '<tr valign="top">' + "\n";
    content += '  <td width="20%"><label for="year">'+$this.t('Year')+'</label></td>' + "\n";
    content += '  <td width="30%">'+yearSelect+'</td>' + "\n";
    content += '  <td width="20%"><label for="month">'+$this.t('Month')+'</label></td>' + "\n";
    content += '  <td width="30%">'+monthSelect+'</td>' + "\n";
    content += '</tr>' + "\n";
    
    content += '</table>' + "\n";

    content += '<div class="EP_list">' + "\n";
    var odd = false;
    var partner = $this.getValue('partner');
    for (var i = 0, len = exList.length; i < len; i++) {
      var df = exList[i].period_date_from.split('-'); // 0-1-2
      var dt = exList[i].period_date_to.split('-');   // 0-1-2
      
      content += '<div class="EP_list_row'+(odd ? ' odd' : ' even')+'">' + "\n";
      content += '  <h3 class="EP_brand"><a href="http://' + $this.getValue('targetHost') + '/Event/lang/'+lang+'/id/'+exList[i].id+'/' +
      	(partner != null ? "?partner=" + partner:"") +
      	'" target="EP_tradeshow">'+exList[i].exName+'</a></h3>' + "\n";
      content += '  <div class="description">' + "\n";
      content += '    <div class="EP_location">'+exList[i].countryName+'/'+exList[i].cityName+'</div>' + "\n";
      content += '    <div class="EP_date">' + "\n";
      content += '      <div class="EP_date_from">'+df[2]+'/'+df[1]+' &#x2014;</div>' + "\n";
      content += '      <div class="EP_date_to">'+dt[2]+'/'+dt[1]+'/'+dt[0]+'</div>' + "\n";
      content += '    </div>' + "\n";
      content += '  </div>' + "\n";
      content += '</div>' + "\n";
      
      odd = !odd;
    }
    content += '</div><div id="EP_footer">&copy; ExpoPromoter, 2010</div>' + "\n";

    $this.container.html(content);

    if ($this.getValue('border')) {
      $this.container.css({'border' : "2px solid " + $this.getValue('border')});
      $($this.containerId + " #EP_trigger").css({'background-color' : $this.getValue('border')});
      $($this.containerId + " #EP_footer").css({'background-color' : $this.getValue('border')});
      $($this.containerId + " .EP_location").css({'color' : $this.getValue('border')});
      $($this.containerId + " .EP_date").css({'color' : $this.getValue('border')});
    }
    
    $($this.containerId + " select").change(EPG_Calendar.updateView);
  },
  
  /*************************************************************************************************/
  
  
  
  run: function() {
    this.updateView();
  }
  
}

EPG_Calendar.load();

