

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

EPJSON.login = '';
EPJSON.passHash = '';
EPJSON.language = 'en';
EPJSON.codepage = 'CP1251';

EPJSON.isOsel = false;

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

	headElement = document.getElementsByTagName("head").item(0); 
	var script = document.createElement("script"); 
	script.setAttribute("type", "text/javascript"); 
	script.setAttribute("src", entryURL);
	headElement.appendChild(script);
}

//Call functions

EPJSON.addExhibitionToSchedule = function(id) {
	if (this.login != '' && this.passHash != '') {
		var data = '{"id": ' + id + '}';
		this.callServer('addExhibitionToSchedule', 'EPJSON.ExhibitionScheduleCallback', data);
		this.writeUpdatingPopUp();
	} else {
		var registerLink = '/vist/User/lang/en/action/register/';
		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>';
		this.writeMessageWindow(message.replace('%LINK_REGISTER%', registerLink));
	}
}

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 {
		this.hideMessageWindow();
		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) {
	document.getElementById('EPMessPopUp').innerHTML = mess;
	this.alignMessageWindow();
	this.showMessageWindow();
}

EPJSON.writeInfoWindow = function(mess) {
	document.getElementById('EPMessPopUp').innerHTML = mess;
	this.alignMessageWindow();
	this.showMessageWindow();
}

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

EPJSON.showMessageWindow = function() {
	document.getElementById('EPMessPopUp').style.visibility = "visible";
}

EPJSON.hideMessageWindow = function() {
	document.getElementById('EPMessPopUp').style.visibility = "hidden";
}

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

	if (win_ie_ver >= 5.5) {
		this.isOsel = true;
		document.write('<div valign="center" id="EPMessPopUp" style="padding: 6px; position:absolute; border:1px solid #DDDDDD; background-color:white; visibility:hidden; width:300px;" onClick="EPJSON.hideMessageWindow();">');
	
		//window.onscroll = EPJSON.alignMessageWindow;
	} else {
		this.isOsel = false;
		document.write('<div valign="center" id="EPMessPopUp" style="padding: 6px; position:fixed; border:1px solid #DDDDDD; background-color:white; opacity:0.9; visibility:hidden; width:300px;" onClick="EPJSON.hideMessageWindow();">');
	}
	
	document.write('</div>');
	
	this.mvObj = document.getElementById('EPMessPopUp');
}

EPJSON.alignMessageWindow = function() {
	var wHeight = document.body.clientHeight;
	var wWidth = document.body.clientWidth;
	
//	var ppHeight = parseInt(this.mvObj.style.height);
	var ppWidth = parseInt(this.mvObj.style.width);

	if (this.isOsel) {
		this.mvObj.style.top = wHeight/2 + document.body.scrollTop;
		this.mvObj.style.right = wWidth/2 - ppWidth/2;
	} else {
		this.mvObj.style.top = wHeight/4;
		this.mvObj.style.right = wWidth/2 - ppWidth/2;
	}
}

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

EPJSON.hidePageElementById = function(id) {
	document.getElementById(id).style.visibility = "hidden";
}

//Баннера

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

EPBANNER.baseExhibitionUrl = '/vist/Exhibition/lang/en/';
EPBANNER.baseSocialOrganisationsUrl = '/vist/SocialOrganisations/lang/en/';
EPBANNER.baseExpoCentersUrl = '/vist/ExpoCenters/lang/en/';
EPBANNER.baseServiceCompaniesUrl = '/vist/ServiceCompanies/lang/en/';

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

		dataOut += '<tr class="ex-odd"><td class="exh-date-end" width="30"><nobr>' + exhib.startDate + " - " + exhib.endDate +
			'</nobr></td><td class="exh-column"><a class="exh-title" style="cursor:pointer;" onClick="EPBANNER.clicker(\'exhibition\', ' + exhib.id + ', ' + bannerId + ');">' + exhib.name +
			'</a></td><td width="90" class="exh-r"><a href="' + EPBANNER.baseExhibitionUrl + 'country/' + exhib.countryId + '/" class="exh-r">' +
			exhib.countryName + '</a>/<a href="' + EPBANNER.baseExhibitionUrl + 'country/' + exhib.countryId + '/city/' + exhib.cityId + '/" class="exh-r">' +
			exhib.cityName + '</a></td><td style="cursor:pointer; width:15px;" align="center" onClick="EPJSON.addExhibitionToSchedule(' + exhib.id + ');">+</td></tr>' + "\n";
			
		dataOut = '<table width="100%">' + dataOut + '</table>';
	
		if (document.getElementById('TopExhibitions')) {
			document.getElementById('TopExhibitions').innerHTML += dataOut;
		} else {
			if (!EPBANNER.banners[bannerId]) {
				EPBANNER.banners[bannerId] = data;
			}
			setTimeout('EPBANNER.show(EPBANNER.banners[' + bannerId + '], ' + bannerId + ')', 500);
		}
	}
}

EPBANNER.clicker = function(type, id, bid) {

	var data = new Object();
	data.bannerId = bid;
	data.referer = window.location.href;
	data.siteIP = '';
	data.hash = 'f0f4392570db53f854e9d8285b20f8a8';

	switch (type) {
		case "exhibition":
			EPBANNER.lastClickURL = EPBANNER.baseExhibitionUrl + 'id/' + id + '/';
			break;
		case "socorg":
			EPBANNER.lastClickURL = EPBANNER.baseSocialOrganisationsUrl + 'socorg/' + id + '/';
			break;
		case "excenter":
			EPBANNER.lastClickURL = EPBANNER.baseExpoCentersUrl + 'excenter/' + id + '/';
			break;
		case "servcomp":
			EPBANNER.lastClickURL = EPBANNER.baseServiceCompaniesUrl + 'servcomp/' + id + '/';
			break;
		default:
			return;
	}

	EPJSON.callServer('bannerClick', 'EPBANNER.redirectToTarget', data.toJSONString());
	EPJSON.writeUpdatingPopUp();
}

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.toJSONString());
	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.toJSONString());
	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.toJSONString());
	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.toJSONString());
	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);	}}

//JSON methods implementations. json.org (c)

if (!Object.prototype.toJSONString) {
    Array.prototype.toJSONString = function () {
        var a = ['['], b, i, l = this.length, v;

        function p(s) {
            if (b) {
                a.push(',');
            }
            a.push(s);
            b = true;
        }

        for (i = 0; i < l; i += 1) {
            v = this[i];
            switch (typeof v) {
            case 'undefined':
            case 'function':
            case 'unknown':
                break;
            case 'object':
                if (v) {
                    if (typeof v.toJSONString === 'function') {
                        p(v.toJSONString());
                    }
                } else {
                    p("null");
                }
                break;
            default:
                p(v.toJSONString());
            }
        }
        a.push(']');
        return a.join('');
    };

    Boolean.prototype.toJSONString = function () {
        return String(this);
    };

    Date.prototype.toJSONString = function () {

        function f(n) {
            return n < 10 ? '0' + n : n;
        }

        return '"' + this.getFullYear() + '-' +
                f(this.getMonth() + 1) + '-' +
                f(this.getDate()) + 'T' +
                f(this.getHours()) + ':' +
                f(this.getMinutes()) + ':' +
                f(this.getSeconds()) + '"';
    };

    Number.prototype.toJSONString = function () {
        return isFinite(this) ? String(this) : "null";
    };

    Object.prototype.toJSONString = function () {
        var a = ['{'], b, i, v;

        function p(s) {
            if (b) {
                a.push(',');
            }
            a.push(i.toJSONString(), ':', s);
            b = true;
        }

        for (i in this) {
            if (this.hasOwnProperty(i)) {
                v = this[i];
                switch (typeof v) {
                case 'undefined':
                case 'function':
                case 'unknown':
                    break;
                case 'object':
                    if (v) {
                        if (typeof v.toJSONString === 'function') {
                            p(v.toJSONString());
                        }
                    } else {
                        p("null");
                    }
                    break;
                default:
                    p(v.toJSONString());
                }
            }
        }
        a.push('}');
        return a.join('');
    };


    (function (s) {
        var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };

        s.parseJSON = function (filter) {
            try {
                if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
                        test(this)) {
                    var j = eval('(' + this + ')');
                    if (typeof filter === 'function') {
                        function walk(k, v) {
                            if (v && typeof v === 'object') {
                                for (var i in v) {
                                    if (v.hasOwnProperty(i)) {
                                        v[i] = walk(i, v[i]);
                                    }
                                }
                            }
                            return filter(k, v);
                        }
                        return walk('', j);
                    }
                    return j;
                }
            } catch (e) {
            }
            throw new SyntaxError("parseJSON");
        };

        s.toJSONString = function () {
            if (/["\\\x00-\x1f]/.test(this)) {
                return '"' + this.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                    var c = m[b];
                    if (c) {
                        return c;
                    }
                    c = b.charCodeAt();
                    return '\\u00' +
                        Math.floor(c / 16).toString(16) +
                        (c % 16).toString(16);
                }) + '"';
            }
            return '"' + this + '"';
        };
    })(String.prototype);
}

// JSON END

// 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;
}



EPJSON.initMessageWindow();