






var EPJSON = new Object();
var EPBANNER = new Object();
var EPADVSRCH = new Object();

EPJSON.login = '';
EPJSON.passHash = '';
EPJSON.language = 'en';
EPJSON.codepage = 'UTF8';
EPJSON.mvObj = null;

EPJSON.isOsel = false;

EPJSON.callServer = function (callMethod, callBackFunc, data) {
  var d = (typeof data == 'string') ? data : $(data).serializeArray();

  var entryURL = "http://ws.expopromoter.com/json/v1/?callMethod=" + callMethod +
                 "&callBackFunc=?" +
                 "&login=" + this.login +
                 "&passHash=" + this.passHash +
                 "&data=" + d +
                 "&lang=" + this.language +
                 "&cp=" + EPJSON.codepage +
                 "&rnd=" + Math.random()*1000000;

  $.getJSON(entryURL, callBackFunc);
}

// Call functions

EPJSON.addExhibitionToSchedule = function(id) {
  if (this.login != '' && this.passHash != '') {
    var data = '{"id": ' + id + '}';
    this.callServer('addExhibitionToSchedule', EPJSON.ExhibitionScheduleCallback, data);
    this.writeUpdatingPopUp();

    this.writeMessageWindow('<center></center>');
  } else {

    
          var registerLink = '/en/User/?action=register';
        var loginLink = '/en/User/?action=login';
    var message = '<p>You are not logged in. Please log in or <a href="%LINK_REGISTER%">register</a>.</p><p>If you had registered you should log in then you can add exhibitions to your calendar.</p>';
    

    message = message.replace('%LINK_REGISTER%', registerLink);
    message = message.replace('%LINK_LOGIN%', loginLink);

    this.writeMessageWindow(message);
  }
}

EPJSON.delExhibitionFromSchedule = function(id) {
  if (this.login != '' && this.passHash != '') {
    var data = '{"id": ' + id + '}';
    this.callServer('delExhibitionFromSchedule', EPJSON.ExhibitionScheduleCallback, data);
    this.writeUpdatingPopUp();
  }
}

EPJSON.getCountriesList = function(id) {
  var data = '{"id": ' + id + '}';
  this.callServer('getCountriesList', EPJSON.ExhibitionCountriesCallback, data);
  this.writeUpdatingPopUp();
}

EPJSON.getCitiesList = function(id) {
  var data = '{"id": ' + id + '}';
  this.callServer('getCitiesList', EPJSON.ExhibitionCitiesCallback, data);
  this.writeUpdatingPopUp();
}

//Callback functions
EPJSON.ExhibitionScheduleCallback = function(result) {
  if (result.data && result.data.errorCode) {
    //For debuging purposes
    this.writeMessageWindow(result.data.errorMessage);
  } else {
    if (result.callMethod == "delExhibitionFromSchedule") {
      this.hidePageElementById('exhibEl_' + result.reqParams.id);
    }
  }
}

EPJSON.ExhibitionCountriesCallback = function(result) {
  //No action must be redefined
}

EPJSON.ExhibitionCitiesCallback = function(result) {
  //No action must be redefined
}



//Extra functions

EPJSON.writeMessageWindow = function(mess) {
  $('#EPMessPopUpContent').html(mess);
  this.alignMessageWindow();
  this.showMessageWindow();
}

EPJSON.writeInfoWindow = function(mess) {
  $('#EPMessPopUpContent').html(mess);
  this.alignMessageWindow();
  this.showMessageWindow();
}

EPJSON.writeUpdatingPopUp = function() {
  this.writeInfoWindow('<center><i>Updating...</i></center>');
}

EPJSON.showMessageWindow = function() {
  $('#EPMessPopUp').show();
}

EPJSON.hideMessageWindow = function() {
  $('#EPMessPopUp').hide();
}

EPJSON.initMessageWindow = function() {
  var win_ie_ver = parseFloat(navigator.appVersion.split("MSIE")[1]);

  var dynamic_html = '<div id="EPMessPopUp" style="padding:0; position:absolute; border:4px solid #999; background-color:#efefef; font-size:12px; display:none; width:320px;">';

  if (win_ie_ver >= 5.5) {
    this.isOsel = true;
    $(dynamic_html).appendTo("body");

    $(window).scroll(EPJSON.alignMessageWindow);
  } else {
    this.isOsel = false;
    $(dynamic_html).appendTo("body");
  }

  $("#EPMessPopUp").append('<div style="text-align:right; background:#999; padding:4px;"><a style="text-decoration:none; font-size:10px; font-weight:bold; color:#efefef;" onclick="EPJSON.hideMessageWindow();" style="cursor:pointer;">X</a></div><div id="EPMessPopUpContent" style="padding:8px 10px 10px 10px;"></div></div>');

  this.mvObj = $('#EPMessPopUp');
}

EPJSON.alignMessageWindow = function() {
  var t = this.mvObj;
  if (t) {
    var wHeight = document.body.clientHeight;
    var wWidth = document.body.clientWidth;

    var ppWidth = parseInt(t.width());

    if (this.isOsel) {
      w_top   = wHeight / 2 + document.body.scrollTop;
      w_right = wWidth / 2 - ppWidth / 2;
    } else {
      w_top   = wHeight / 6;
      w_right = wWidth / 2 - ppWidth / 2;
    }

    t.css('top', w_top + "px");
    t.css('right', w_right + "px");
  }
}

EPJSON.setSizeMessageWindow = function(width) {
  this.mvObj.width(width);
}

EPJSON.hidePageElementById = function(id) {
  $("#" + id).hide();
}





EPJSON.oE = function(id) {
  window.open(EPBANNER.baseEventUrl + 'source/calendar/id/' +id + '/', 'exw'+id, 'width=950, height=740, status=no,resizable=yes, scrollbars=yes');
}



EPJSON.iHoHoComp = function(id, compid, mode) {
  window.open(EPBANNER.baseEventUrl + 'source/calendar/id/' +id + '/mode/' +mode+ '/adid/' +compid+ '/', 'exw'+id, 'width=950, height=740, status=no,resizable=yes, scrollbars=yes');
}


//Баннера

EP_BO.putPriorityLine = function(BPlace) {
  this.bannerPlaceId++;
  var bannerPlaceName = "EP_BP"+this.bannerPlaceId;
  document.write("<tr id='" + bannerPlaceName + "'></tr>");
  this.jsonMakeBannerRequest(BPlace, bannerPlaceName);
}

EP_BO.putPriorityStart = function() {
  document.write('<table class="list" style="background:none; margin:0px;" cellpadding="0" cellspacing="0" border="0" width="100%">');
}

EP_BO.putPriorityEnd = function() {
  document.write('</table>');
}


EPBANNER.data = null;
EPBANNER.lastClickURL = null;
EPBANNER.banners = new Array();

EPBANNER.baseExhibitionUrl = '/en/Event/';
EPBANNER.baseEventUrl = '/en/Event/';

EPBANNER.baseSocialOrganisationsUrl = '/en/SocialOrganisations/';
EPBANNER.baseExpoCentersUrl = '/en/ExpoCenters/';
EPBANNER.baseServiceCompaniesUrl = '/en/ServiceCompanies/';

EPBANNER.show = function(data, bannerId, elementID) {
  var dataOut = '';
  var i = 0;

  if (data.exhibition) {
    exhib = data.exhibition;
    url = this.getGoUrl('exhibition', exhib);

    var dstart = exhib.startDate.split('-');
    var dend   = exhib.endDate.split('-');
    dstart = 'en' == 'ru' ? (dstart[2] + '.' + dstart[1]) : (dstart[1] + '/' + dstart[2]);
    dend   = 'en' == 'ru' ? (dend[2] + '.' + dend[1] + '.' + dend[0]) : (dend[1] + '/' + dend[2] + '/' + dend[0]);

    ds = dstart[0] + dstart[1] + dstart[2];
    de = dend[0] + dend[1] + dend[2];

    dataOut = '<td width="140" style="white-space:nowrap;"><div class="date"><strong>' + dstart + " - " + dend +
      '</strong></td><td class="body"><h3><a href="' + url + '">' + exhib.name +
      '</a></h3></td><td width="120" style="white-space:nowrap;"><div class="location">' + exhib.countryName + ' | ' + exhib.cityName + '</div></td>' +
      '<td style="cursor:pointer; width:15px;" align="center" onclick="EPJSON.addExhibitionToCalendars(' + exhib.id + ', \'' + exhib.name + '\', \'' + ds + '\', \'' + de + '\', \'' + exhib.countryName + ', ' + exhib.cityName + '\'); return false;"><img src="/images/ico_fav.jpg" alt="Add to calendar" /></td>';

    if ($("#" + elementID).length) {
      $("#" + elementID).html(dataOut);
    }
  }
}

EPBANNER.getGoUrl = function(type, data) {
  var url = data.url + "_dummy?go=http://" + document.location.hostname;

  switch (type) {
    case "exhibition":
      url += EPBANNER.baseExhibitionUrl + 'id/' + data.id + '/';
      break;
  }

  return url;
}

EPBANNER.redirectToTarget = function(data) {
  EPJSON.hideMessageWindow();

  window.location.href = EPBANNER.lastClickURL;
}



//Расширеный поиск

EPADVSRCH.getSubCategoriesList = function(catObj) {

  var data = this.getObjectSelectedItems(catObj);

  EPJSON.callServer('getSubCategoriesList', EPADVSRCH.getSubCategoriesListCallBack, data);
  EPJSON.writeUpdatingPopUp();
}

EPADVSRCH.getSubCategoriesListCallBack = function(result) {
  var subCatsObj = document.getElementById('subCategories');
  var catsObj = document.getElementById('categories');

  this.fillSelectWhithData(catsObj, subCatsObj, result);

  EPJSON.hideMessageWindow();
}

EPADVSRCH.getCountriesList = function(Obj) {

  var data = this.getObjectSelectedItems(Obj);

  EPJSON.callServer('getCountriesList', EPADVSRCH.getCountriesListCallBack, data);
  EPJSON.writeUpdatingPopUp();
}

EPADVSRCH.getCountriesListCallBack = function(result) {
  var regionsObj = document.getElementById('regions');
  var countriesObj = document.getElementById('countries');
  var citiesObj = document.getElementById('cities');
  var exCentersObj = document.getElementById('exCenters');

  this.DeleteAllChild(citiesObj);
  this.DeleteAllChild(exCentersObj);

  this.fillSelectWhithData(regionsObj, countriesObj, result);

  EPJSON.hideMessageWindow();
}

EPADVSRCH.getCitiesList = function(Obj) {

  var data = this.getObjectSelectedItems(Obj);

  EPJSON.callServer('getCitiesList', EPADVSRCH.getCitiesListCallBack, data);
  EPJSON.writeUpdatingPopUp();
}

EPADVSRCH.getCitiesListCallBack = function(result) {
  var countriesObj = document.getElementById('countries');
  var citiesObj = document.getElementById('cities');
  var exCentersObj = document.getElementById('exCenters');

  this.DeleteAllChild(exCentersObj);

  this.fillSelectWhithData(countriesObj, citiesObj, result);

  EPJSON.hideMessageWindow();
}

EPADVSRCH.getExCentersList = function(Obj) {

  var data = this.getObjectSelectedItems(Obj);

  EPJSON.callServer('getExCentersList', EPADVSRCH.getExCentersListCallBack, data);
  EPJSON.writeUpdatingPopUp();
}

EPADVSRCH.getExCentersListCallBack = function(result) {
  var exCentersObj = document.getElementById('exCenters');
  var citiesObj = document.getElementById('cities');

  this.fillSelectWhithData(citiesObj, exCentersObj, result);

  EPJSON.hideMessageWindow();
}

EPADVSRCH.fillSelectWhithData = function(parentObj, Obj, result) {
  var Data = new Array();
  var Index = 0;

  this.DeleteAllChild(Obj);

  for (i=0; i < result.data.length; i++) {
    Data = result.data[i].data;

    var newOptGroup = document.createElement('OPTGROUP');
    newOptGroup.label = this.getObjectTextByValue(parentObj, result.data[i].parentId);
    Obj.appendChild(newOptGroup);

    for (j=0; j < Data.length; j++) {
      Obj.options[Index] = new Option(Data[j].name, Data[j].id);
      Index++;
    }
  }
}

EPADVSRCH.getObjectSelectedItems = function(obj) {
  var result = new Array();
  for (i=0; i < obj.length; i++) {
    if (obj.options[i].selected == true) {
      result.push(obj.options[i].value);
    }
  }

  return result;
}

EPADVSRCH.getObjectTextByValue = function (obj, value) {
  var i = 0;
  var res = '';

  do {
    if (obj.options[i].value == value) {
      res = obj.options[i].text;
    }
    i++;
  } while (i < obj.length && res == '')

  return res;
}

EPADVSRCH.DeleteAllChild = function(sel) {
  sel.options.length = 0;

  while (sel.childNodes.length) {
    if (sel.firstChild.tagName == 'OPTGROUP') {
      while (sel.firstChild.childNodes.length) {
        sel.firstChild.removeChild(sel.firstChild.firstChild);
      }
    }
    sel.removeChild(sel.firstChild);
  }
}




// Flash
function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?');
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs)
{
  var str = '<' + 'object ';
  for (var i in objAttrs)
    str += i + '="' + objAttrs[i] + '" ';
  str += '>';
  for (var i in params)
    str += '<param name="' + i + '" value="' + params[i] + '" /> ';
  str += '<' + 'embed ';
  for (var i in embedAttrs)
    str += i + '="' + embedAttrs[i] + '" ';
  str += ' ></embed></object>';

  document.write(str);
}

function AC_FL_RunContent(){
  var ret =
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
    , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret =
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
    , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();

    switch (currArg){
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace":
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "id":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}





var default_country = 0;

EPJSON.targetElement = false;

EPJSON.ExhibitionCountriesCallback = function(result) {
  var resLen = result.data.length;
  var obj = EPJSON.targetElement;

  if (!obj) return;

  if (resLen > 1) {
    obj.disabled = false;
    obj.options.length = 0;
    obj.options[0]=new Option('- select country -');
    obj.options[0].value = '';

    for (i=0; i < resLen; i++) {
      obj.options[i+1]=new Option(result.data[i].name);
      obj.options[i+1].value = result.data[i].id;
    }
  } else {
    obj.disabled = true;
    obj.options.length = 0;
    obj.options[0]=new Option('- select country -');
  }

  EPJSON.hideMessageWindow();
}

EPJSON.ExhibitionCitiesCallback = function(result) {
  var resLen = result.data.length;
  var obj = EPJSON.targetElement;

  if (!obj) return;

  if (resLen>0) {
    obj.disabled = false;
    obj.options.length = 0;
    obj.options[0]=new Option('- select city -');
    obj.options[0].value = '';

    for (i=0; i < resLen; i++) {
      obj.options[i+1]=new Option(result.data[i].name);
      obj.options[i+1].value = result.data[i].id;
    }
  } else {
    obj.disabled = true;
    obj.options.length = 0;
    obj.options[0]=new Option('- select city -');
  }

  EPJSON.hideMessageWindow();
}


$(document).ready(
  function () {
    EPJSON.initMessageWindow();

    $("#filter_form").submit(
      function () {
        var url = "/en/Exhibition/?";
        var f = this;

        if (f.search.value && f.search.value != 'event name or keyword')   url += 'search=' + f.search.value + '&';
        if (f.category.value) url += 'category=' + f.category.value + '&';
        if (f.region.value)   url += 'region=' + f.region.value + '&';
        if (f.country.value)  url += 'country=' + f.country.value + '&';
        if (f.city.value)     url += 'city=' + f.city.value + '&';

        if (f.date_from.value && f.date_from.value != '- beginning date -') url += 'datefrom=' + f.date_from.value + '&';
        if (f.date_to.value && f.date_to.value != '- ending date -') url += 'dateto=' + f.date_to.value + '&';

        location.href = url;
        return false;
      }
    );

    $("#search_field").blur(
      function () {
        if ($(this).val() == '') $(this).val('event name or keyword');
      }
    );

    $("#search_field").focus(
      function () {
        if ($(this).val() == 'event name or keyword')
        $(this).val('');
      }
    );

    $(".date-pick").blur(
      function () {
        if ($(this).val() == '') $(this).val(this.id == 'start-date' ? '- beginning date -' : '- ending date -');
      }
    );

    $(".date-pick").focus(
      function () {
        if ($(this).val().indexOf('date') != -1) $(this).val('');
      }
    );

    $("#region").change(
      function () {
        var region = $(this).val();

        // opera.postError('Region has been changed');

        if (region) {
          $("#city").html('<option value="">- select country first -</option>');

          EPJSON.targetElement = $("#country")[0];
          EPJSON.getCountriesList(region);
        } else {
          $("#country").html('<option value="">- select region first -</option>');
          $("#city").html('<option value="">- select country first -</option>');
        }
      }
    );

      $("#country").change(
      function () {
        var country = $(this).val();
        var region = $("#region").val();

        // opera.postError('Country has been changed');

        if (country) {
          EPJSON.targetElement = $("#city")[0];
          EPJSON.getCitiesList(country);
        } else {
          $("#city").html('<option value="">- select country first -</option>');
        }
      }
    );

    // Customize two date pickers to work as a date range
    function customRange(input) {
      return {minDate: (input.id == 'end-date' ? $('#start-date').datepicker('getDate') : null),
        maxDate: (input.id == 'start-date' ? $('#end-date').datepicker('getDate') : null)};
    }

    $.datepicker.setDefaults({showOn: 'both', buttonImageOnly: true, buttonImage: '/images/calendar-icon.gif', buttonText: 'Calendar', beforeShow: customRange, prevText: '<<', nextText: '>>', dateFormat: 'dd-mm-yy'});

    $(".date-pick").datepicker();

    $("#search_field").blur();
    $(".date-pick").blur();
  }
);


