var My = new function()
	{
	// days to store cookie
	this.days = 30;
    this.currentActiveDiv = null;

	// cookie functions - taken from quirksmode.org/...
	this.createCookie = function(name, value, days)
		{
		if(days)
			{
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			var expires = "; expires="+date.toGMTString();
			}
		else
			var expires = "";

		document.cookie = name+"="+value+expires+"; path=/";
		}

	this.readCookie = function(name)
		{
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');

		for(var i = 0, ic = ca.length; i < ic; ++ i)
			{
			var c = ca[i];

			while(c.charAt(0) == ' ')
				c = c.substring(1, c.length);

			if(c.indexOf(nameEQ) == 0)
				return c.substring(nameEQ.length, c.length);
			}

		return null;
		}

	this.eraseCookie = function(name)
		{
		this.createCookie(name,"",-1);
		}

	// initializing script - take cookie string and splits it into objects list
	this.total = 0;
	this.list = {};
	this.sections = new Array();
	this.subsections = {};

	var list = decodeURIComponent(this.readCookie('my_list'));
	if(list)
		{
		var entriesAr = list.split(',');
		for(var i = 0, ic = entriesAr.length; i < ic; ++ i)
			{
			var tokens = entriesAr[i].split('_');
			if(tokens.length != 3)
				continue;

			if(!this.list[tokens[0]])
				{
				this.list[tokens[0]] = {};
				this.sections.push(tokens[0]);
				this.subsections[tokens[0]] = new Array();
				}

			if(!this.list[tokens[0]][tokens[1]])
				{
				this.list[tokens[0]][tokens[1]] = new Array();
				this.subsections[tokens[0]].push(tokens[1]);
				}

			this.list[tokens[0]][tokens[1]].push(tokens[2]);
			++ this.total;
			}
		}

	var agt = navigator.userAgent.toLowerCase();
	this.ie = false;

	if(agt.indexOf("msie") != -1)
	    this.ie = true;

	// initialize search lists
	this.savedSearchTotal = 0;
	this.savedSearchList = [];

	var list = decodeURIComponent(this.readCookie('my_search_list'));
	if(list)
		{
		var entriesAr = list.split(';');
		for(var i = 0, ic = entriesAr.length; i < ic; ++ i)
			{
			var tokens = entriesAr[i].split('!');
			if(tokens.length != 2)
				continue;

			this.savedSearchList.push({url: tokens[0], name: tokens[1].replace(/\+/g, ' ')}); 
			++ this.savedSearchTotal;
			}
		}

	// search the list for occurence of the object with specified params
	this.searchList = function(section, subsection, id)
		{
		var pos = -1;
		if(this.list[section] && this.list[section][subsection] && (pos = this.list[section][subsection].indexOf(id)) >= 0)
			return pos;

		return -1;
		}

	// inserts checkbox, checked if it is presented in the list
	this.checkbox = function(section, subsection, id, loggedIn)
		{
		document.write("<input id=\"chk_" + section + "_" + subsection + "_" + id + "\" type=\"checkbox\"" + (this.searchList(section, subsection, id) != -1 ? " checked=\"checked\"" : "") + "/>");
		var chk = $("chk_" + section + "_" + subsection + "_" + id);

        if(loggedIn == true)
            {
            Event.observe(chk, "change", My.checkboxChange.bindAsEventListener(this));
            if(this.ie)
                Event.observe(chk, "click", My.checkboxChange.bindAsEventListener(this));
            }
        else
            {
            Event.observe(chk, "click", My.checkboxRestrict.bindAsEventListener(this));
            }
		}

    this.restrictSaveSearch = function(event)
        {
        if(this.currentActiveDiv != null)
            this.currentActiveDiv.setStyle({display: 'none'});

        if(null != document.getElementById('saveSearchDiv'))
            document.getElementById('saveSearchDiv').style.display = 'block';
        else
            {
            var div = $(document.createElement('div'));
            this.currentActiveDiv = div;
            div.id = 'saveSearchDiv';
            div.setStyle({position: 'absolute', left: (event.clientX - 200) + 'px', top: (event.clientY + 25) + 'px', background: 'white', padding: '10px', border: '1px solid #999'});
            div.innerHTML = 'Функция доступна только зарегистрированным пользователям.<br/><a href="/cabinet/">Входите</a> или <a href="/cabinet/register">зарегистрируйтесь</a>.<br/><a onclick="document.getElementById(\'saveSearchDiv\').style.display=\'none\'; return false;" href="." style="display: block; text-align: center; padding-top: 5px; color: red;">закрыть</a>';
            document.body.appendChild(div);

            Event.stop(event);
            }

        }
		
	this.restrictSaveSearch2 = function(event)
        {
        if(this.currentActiveDiv != null)
            this.currentActiveDiv.setStyle({display: 'none'});

        if(null != document.getElementById('saveSearchDiv'))
            document.getElementById('saveSearchDiv').style.display = 'block';
        else
            {
            var div = $(document.createElement('div'));
            this.currentActiveDiv = div;
            div.id = 'saveSearchDiv';
            div.setStyle({position: 'absolute', left: (event.clientX - 200) + 'px', top: (event.clientY + 25) + 'px', background: 'white', padding: '10px', border: '1px solid #999'});
            div.innerHTML = 'Функция доступна только зарегистрированным пользователям.<br/><a href="/cabinet/">Входите</a> или <a href="/cabinet/register">зарегистрируйтесь</a>.<br/><a onclick="document.getElementById(\'saveSearchDiv\').style.display=\'none\'; return false;" href="." style="display: block; text-align: center; padding-top: 5px; color: red;">закрыть</a>';
            document.body.appendChild(div);

            Event.stop(event);
            }

        }

	// listener - observes for checkbox CHANGE events 
	this.checkboxChange = function(event)
		{
		var chk = Event.element(event);

		var tokens = chk.id.substring(4).split('_');
		if(tokens.length != 3)
			return;

		if(chk.checked)
			{
			if(this.searchList(tokens[0], tokens[1], tokens[2]) == -1)
				{
				this.addEntry(tokens[0], tokens[1], tokens[2]);
				}
			}
		else
			{
			if(this.searchList(tokens[0], tokens[1], tokens[2]) != -1)
				{
				this.removeEntry(tokens[0], tokens[1], tokens[2]);
				}
			}
		}

    this.checkboxRestrict = function(event)
		{
        var chk = Event.element(event);

        if(this.currentActiveDiv != null)
            this.currentActiveDiv.setStyle({display: 'none'});

        if(null != document.getElementById(chk.id + '_div'))
            document.getElementById(chk.id + '_div').style.display = 'block';
        else
            {
            var div = $(document.createElement('div'));
            this.currentActiveDiv = div;
            div.id = chk.id + '_div';
            div.setStyle({position: 'absolute', left: (event.clientX - 200) + 'px', top: (event.clientY + document.documentElement.scrollTop - 25) + 'px', background: 'white', padding: '10px', border: '1px solid #999', zIndex: '100'});
            div.innerHTML = 'Функция доступна только зарегистрированным пользователям.<br/><a href="/cabinet/">Входите</a> или <a href="/cabinet/register">зарегистрируйтесь</a>.<br/><a onclick="document.getElementById(\'' + div.id + '\').style.display=\'none\'; return false;" href="." style="display: block; text-align: center; padding-top: 5px; color: red;">закрыть</a>';
            document.body.appendChild(div);

            }

        Event.stop(event);
		}

	// adds entry to the list and cookie
	this.addEntry = function(section, subsection, id)
		{
		if(!this.list[section])
			{
			this.list[section] = {};
			this.sections.push(section);
			this.subsections[section] = new Array();
			}

		if(!this.list[section][subsection])
			{
			this.list[section][subsection] = new Array();
			this.subsections[section].push(subsection);
			}
		
		this.list[section][subsection].push(id);
		++ this.total;
		
		this.updateCookie();
		
		var THIS = this;
		this.totalLinks.each(
			function(link)
				{
				link.update(THIS.generateLinkText(THIS.total));
				if(THIS.total > 0)
					link.setStyle({display: "inline"});
				}
			);
		}

	// removes entry from the list and cookie
	this.removeEntry = function(section, subsection, id)
		{
		var pos = -1;
		if(!this.list[section] || !this.list[section][subsection] || (pos = this.list[section][subsection].indexOf(id)) == -1)
			{
			return;
			}

		this.list[section][subsection].splice(pos, 1);

		-- this.total;
		if(this.total < 0)
			this.total = 0;

		if(this.list[section][subsection].length == 0)
			{
			delete(this.list[section][subsection]);
			this.subsections[section].splice(this.subsections[section].indexOf(subsection), 1);
			
			if(this.subsections[section].length == 0)
				{
				delete(this.subsections[section]);
				delete(this.list[section]);
				this.sections.splice(this.sections.indexOf(section), 1);
				}
			}
		
		this.updateCookie();

		var THIS = this;
		this.totalLinks.each(
			function(link)
				{
				link.update(THIS.generateLinkText(THIS.total));
				if(THIS.total < 1)
					link.setStyle({display: "none"});
				}
			);
		}

	// serializes the list values and writes it to cookie
	this.updateCookie = function()
		{
		var s = "";
		var THIS = this;

		this.sections.each(
			function(section)
				{
				THIS.subsections[section].each(
					function(subsection)
						{
						THIS.list[section][subsection].each(
							function(id)
								{
								s += section + "_" + subsection + "_" + id + ",";
								}
							);
						}
					);
				}
			);

		this.createCookie("my_list", s, this.days);
		}

	// displays link with number of selected entries
	this.totalLinks = new Array();
	this.totalLink = function(href)
		{
		

		document.write("<a id=\"total_link_" + this.totalLinks.length + "\" href=\"" + href + "\" class=\"my_link\">" + this.generateLinkText(this.total) + "</a>");
		var link = $("total_link_" + this.totalLinks.length);
		this.totalLinks.push(link);

		if(this.total < 1)
			link.setStyle({display: "none"});
		}

	// generates text "You've got XX selected ads"
	this.generateLinkText = function(total)
		{
		var mod10 = total % 10;
		var mod100 = total % 100;
		if(mod10 == 1 && mod100 != 11)
			{
			suff1 = 'ое';
			suff2 = 'е';
			}
		else if(mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14))
			{
			suff1 = 'ых';
			suff2 = 'я';
			}
		else
			{
			suff1 = 'ых';
			suff2 = 'й';
			}

		return "У вас " + total + " отмеченн" + suff1 + " объявлени" + suff2;
		}

	// generates saved search links
	this.totalSavedSearchLinks = [];
	this.savedSearchLinks = function()
		{
		for(var i = 0, ic = this.savedSearchList.length; i < ic; ++ i)
			{
			if(i == 0)
                document.write("<strong>Сохраненные поисковые запросы:</strong><br/>");

            var obj = this.savedSearchList[i];
			document.write("<div class=\"small saved_search\" id=\"saved_search_" + this.totalSavedSearchLinks.length + "\"><a style=\"color:red; text-decoration: none\" title=\"Удалить\" href=\"#\" onclick=\"My.removeSavedSearch(this, " + i + "); return false;\">&times;</a> <a href=\"" + obj.url + "\">" + obj.name + "</a></div>");
			var link = $("saved_search_" + this.totalSavedSearchLinks.length);
			this.totalSavedSearchLinks.push(link);
			}

        document.write("<br/>");
		}

	// removes saved search entry
	this.removeSavedSearch = function(link, i)
		{
		if(this.totalSavedSearchLinks[i])
			{
			this.totalSavedSearchLinks[i].hide();
			this.totalSavedSearchLinks[i] = null;
			this.savedSearchList[i].url = null;
			this.updateSavedSearchCookie();
			}
		}

	// updates saved search cookie with new value
	this.updateSavedSearchCookie = function()
		{
		var s = "";
		var THIS = this;
	
		this.savedSearchList.each(
			function(savedSearch)
				{
				if(savedSearch.url)
					s += savedSearch.url + "!" + savedSearch.name + ";"; 
				}
			);

		this.createCookie("my_search_list", encodeURIComponent(s), this.days);
		}
	}



// Poper class :)
function RPop(id)
	{
	this.id = id;
	this.inner = $("pop_" + id);
	this.showLink = $("pop_show_" + id);
	this.closeLink = $("pop_close_" + id);
	this.outer = $("pop_outer_" + id);

	Event.observe(this.showLink, "click", this.show.bindAsEventListener(this));
	Event.observe(this.closeLink, "click", this.close.bindAsEventListener(this));
	}

RPop.prototype =
	{
	show: function(event)
		{
		if(event)
			Event.stop(event);

		if(RPop.active == this)
			return;

		if(RPop.active)
			RPop.active.close(null);

		this.inner.show();
		this.outer.setStyle({zIndex: 1});

		RPop.active = this;
		},

	close: function(event)
		{
		if(event)
			Event.stop(event);

		this.inner.hide();
		this.outer.setStyle({zIndex: 0});

		if(RPop.active == this)
			RPop.active = null;
		}
	};

RPop.active = null;
