if (window.Autocompleter)
{
	Autocompleter.Base.prototype.markPrevious = function() {
		if(this.index > 0) this.index--;
		  else this.index = this.entryCount-1;
		this.getEntry(this.index).scrollIntoView(false);
	};
}


var AjaxForm = Class.create({

	initialize: function(form)
	{
		this.domForm = $(form);
		this.initDom();
		this.domForm.fire('popup:update');
	},

	initDom: function()
	{
		this.domForm.observe('submit', this.onSubmit.bindAsEventListener(this));
	},

	onSubmit: function(event)
	{
		event.stop();
		this.domForm.request({
			onSuccess: this.onRequestSuccess.bind(this),
			onFailure: this.onRequestFailure.bind(this)
		});
	},

	onRequestSuccess: function(res)
	{
		this.domForm.replace(res.responseText);
	},

	onRequestFailure: function(res)
	{
		alert('Fail!');
	}

});



var VisitorsCounter = Class.create({
    initialize: function(container, users_online)
    {
        this.startValue = users_online;
        this.delay = 3;
        this.step = 3;

        this.domContainer = $(container);

        new PeriodicalExecuter(this.update.bind(this), this.delay);
    },

    update: function()
    {
        this.startValue = this.startValue + Math.round((Math.random()*2 - 1)*this.step);
        this.domContainer.update(this.startValue + "");
    }
});

var DownloadsCounter = Class.create({
        initialize: function(container)
        {
            this.startDate = new Date(2008, 8, 15, 0, 0, 0);

            this.startValue = 41173296;
            this.downloadsPerSecond = 1;


            this.startTimestamp = this.startDate.getTime()/1000;
            this.domContainer = $(container);
            this.updateCounterBound = this.updateCounter.bind(this);

            this.updateCounter();
        },

        updateCounter: function ()
        {
            this.currentTimestamp = new Date().getTime()/1000;

            var currentValue = Math.round(this.startValue + (this.currentTimestamp - this.startTimestamp)*this.downloadsPerSecond);

            //format string a bit
            var currentValueStr = currentValue+"";
            var currentValueStrFormatted = "";

            for (var i = currentValueStr.length-1, j=0; i >= 0; i--,j++)
            {
                currentValueStrFormatted = currentValueStr.charAt(i)+currentValueStrFormatted;
                if ((j+1)%3 == 0)
                    currentValueStrFormatted = '<b style="visibility: hidden;">,</b>'+currentValueStrFormatted;
            }





            this.domContainer.update(currentValueStrFormatted);

            //delay between 0 and 2 seconds...
            //short dalays is more probable than long ones
            var delay = Math.pow(Math.random(), 4)*2;

            //console.log(delay);
            setTimeout(this.updateCounterBound, Math.round(delay*1000));
        }

    });


function addAutoComplete() {
	/*
    new Ajax.Autocompleter('search', 'search_res', '/api/search.php?m=json', {
        paramName: 's',
        minChars: 3,
        afterUpdateElement: function () {
            $('search_res').show();
        }
    });*/
    if ($('top_search') && $('top_search_res')) {
    	new inputText($('top_search'), str_search);
        new Ajax.Autocompleter('top_search', 'top_search_res', '/api/search.php?m=json', {
            paramName: 's',
            minChars: 3,
            afterUpdateElement: function () {
                $('top_search_res').show();
            }
        });
    }

}

var inputText = Class.create({
	initialize: function(element, text)
	{
		this.element = element;
		this.text = text;
		this.showText();
		this.element.observe('focus', this.hideText.bind(this));
		this.element.observe('blur', this.showText.bind(this));
		this.element.observe('input_text:hide', this.hideText.bind(this));
		this.element.observe('input_text:show', this.showText.bind(this));
	},
	hideText: function() {
		if (this.element.value == this.text) {
			this.element.value = '';
		}
	},
	showText: function() {
		if (this.element.value == '') {
			this.element.value = this.text;
		}
	}
});



var ClickTracker = Class.create({
	initialize: function()
	{
		//document.observe('dom:loaded', this.onLoad.bindAsEventListener(this));
	},

	track: function()
	{
		document.observe('click', this.onClick.bindAsEventListener(this));

		Event.observe(window, 'unload', this.sendClicks.bind(this));
		new PeriodicalExecuter(this.sendClicks.bind(this), 15);

		this.trackedClicks = [];
	},

	show: function()
	{
		this.domClicksContainer = new Element('div', {'class': 'x-clicks-container'});
		this.domClicksContainer.style.position = 'absolute';
		this.domClicksContainer.style.overflow = 'visible';
		document.body.appendChild(this.domClicksContainer);

		this.domPageForm = new Element('form', {method: 'post', action: ''});
		var domTextbox = new Element('input', {type: 'text', name: 'page', size: '100', value: this.getPage()});
		var domButton = new Element('input', {type: 'submit', value: 'go'});

		this.domPageForm.appendChild(domTextbox);
		this.domPageForm.appendChild(domButton);
		document.body.appendChild(this.domPageForm);

		this.domPageForm.observe('submit', function(event) {
			this.loadClicks(domTextbox.value);
			event.stop();
		}.bindAsEventListener(this));


		this.loadClicks();


		Event.observe(window, 'load', this.fixClicksContainerPos.bind(this));
		Event.observe(window, 'resize', this.fixClicksContainerPos.bind(this));
	},

	loadClicks: function(page)
	{
		if (!page)
			page = this.getPage();

		new Ajax.Request('/clicks.php', {parameters: {action: 'show', page: page}, onSuccess: this.onClicksLoaded.bind(this)});
	},

	fixClicksContainerPos: function()
	{
		this.domClicksContainer.clonePosition(this.getFirstElement(), {setWidth: false, setHeight:false});

		var firstDomClick = this.domClicksContainer.down('b');
		if (firstDomClick)
		{
			var dim = firstDomClick.getDimensions();
			this.domClicksContainer.style.left = (parseInt(this.domClicksContainer.style.left) - dim.width/2)+'px';
			this.domClicksContainer.style.top = (parseInt(this.domClicksContainer.style.top) - dim.height/2)+'px';
		}
	},

	onClicksLoaded: function(res)
	{
		this.domClicksContainer.innerHTML = '';

		var clicks = res.responseJSON;
		for (var i = 0; i < clicks.length; i++)
		{
			var domClick = new Element('b');
			domClick.style.left = (clicks[i].x)+'px';
			domClick.style.top = (clicks[i].y)+'px';

			this.domClicksContainer.appendChild(domClick);
		}

		this.fixClicksContainerPos();
	},


	onClick: function(event)
	{
		var domFirst = this.getFirstElement();
		var offset = domFirst.cumulativeOffset();
		var pointer = event.pointer();

		var data = {
			x: pointer.x - offset.left,
			y: pointer.y - offset.top
		}

		this.trackedClicks.push(data);
	},

	sendClicks: function()
	{
		if (this.trackedClicks.length == 0)
			return;

		var params = {
			action: 'track',
			'x[]': [],
			'y[]': [],
			page: this.getPage()
		};

		for (var i = 0; i < this.trackedClicks.length; i++)
		{
			params['x[]'].push(this.trackedClicks[i].x);
			params['y[]'].push(this.trackedClicks[i].y);
		}

		new Ajax.Request('/clicks.php', {parameters: params});
		this.trackedClicks = [];
	},

	getPage: function()
	{
		var tmp =  document.location.pathname+document.location.search;
		return tmp;
	},

	getFirstElement: function()
	{
		return $(document.body).down();
	}
});



function showPopup(href, w, h, options)
{
	name = name || 'popup';

	var defaultOptions = $H({
			name: 'popup',
			scrollbars: 'no',
			resizable: 'yes'
	});

	options = defaultOptions.merge(options);
	options = options.merge({width:w, height: h});

	var name = options.unset('name');


	var optionsStr = '';
	options.each(function(pair) {optionsStr += pair.key+'='+pair.value+','});
	optionsStr = optionsStr.replace(/,$/, ''); //replace the trailing comma

	window.open(href, name, optionsStr);

	return false;
}


function fixSidebarBlocksSizes()
{
	//if right sidebar is too short add some length
	var domRightCol = $('rightCol');
	var domCenterCol = $('centerCol');

	if (!domRightCol)
		return;

	if (domCenterCol.offsetHeight > domRightCol.offsetHeight)
	{
		var domLastRightChild = domRightCol.down('.cont:last-child');
		if (domLastRightChild)
		{
				domLastRightChild.style.height = parseInt(domLastRightChild.getStyle('height'))+(domCenterCol.offsetHeight-domRightCol.offsetHeight)+'px';
		}
	}

}


var DevicePopup = Class.create(Popup, {
	initialize: function($super, options)
	{
		$super(options);
		this.domPopup.addClassName('device-popup');
	}
});


var DeviceSelector = Class.create({
   initialize: function()
   {
    this.domContainer = $('select_device');
       this.domVendorSelect = this.domContainer.down('select[name=devicemaker_id]');
       this.domDeviceImg = this.domContainer.down('img.device_img');
       this.domVendorForm = this.domVendorSelect.up('form');

       this.domActionInput = this.domContainer.down('input[name=action]');

       //remove old handler and add new one to device's vendor select
       this.domVendorSelect.onchange = '';
       this.domVendorSelect.writeAttribute('onchange', '');
       this.domDeviceImg.observe('click', this.onImageClick.bindAsEventListener(this));
       this.domVendorSelect.observe('change', this.onVendorChange.bindAsEventListener(this));
   },

   onImageClick: function(event)
   {
//	   if ($F(this.domVendorSelect) == '')
//		   return;


	   this.domVendorSelect.style.backgroundColor='#FFFFAF';
	   this.domVendorSelect.focus();
	   //this.request = this.domVendorForm.request({onSuccess: this.onVendorChangeSuccess.bind(this)});
   },


   onVendorChange: function(event)
   {

	   if ($F(this.domVendorSelect) == '')
            return;



	   if ($F(this.domVendorSelect) == '-1')
	   {
		   this.domActionInput.value='clear';
		   this.domVendorForm.submit();
		   return;
	   }


	   this.request = this.domVendorForm.request({onSuccess: this.onVendorChangeSuccess.bind(this)});
   },

   onVendorChangeSuccess: function(resp)
   {
	   if (this.devicePopup && this.devicePopup.isClosed())
	   {
		   this.devicePopup.close();
	   }

	   this.devicePopup = new DevicePopup({title: 'Select Device', html: resp.responseText});
   }




});

if (window.Autocompleter)
{
	Autocompleter.DeviceSelectDialog = Class.create(Ajax.Autocompleter, {

		//the same as original but w/o ie fix
		show: function()
		{
			if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
		},

		markPrevious: function($super)
		{
			if(this.index > 0) this.index--;
			  else this.index = this.entryCount-1;
			this.getEntry(this.index).scrollIntoView(false);
		}
	});
}



var DeviceSelectDialog = Class.create({
	initialize: function(form)
	{
		this.domForm = $(form);
		this.domTextbox = this.domForm.down('input[name=q]');
		this.domModelIdInput = this.domForm.down('input[name=model_id]');
		this.domModels = this.domForm.down('.models');
		this.domShowPopular = this.domForm.down('.show-popular');

		this.domForm.appendChild(new Element('input', {type: 'hidden', name: 'return_to', value: document.location.pathname}));


		this.domTextbox.focus();

		this.domShowPopular.observe('click', this.showPopular.bindAsEventListener(this));

		this.autocompleter = new Autocompleter.DeviceSelectDialog(this.domTextbox, this.domModels, "/devices.php?action=show_list2", {
			frequency: 0.3,
			updateElement: this.onAutocompleterUpdate.bind(this)
		});

		this.domForm.select('.textbox-example').each(function(example) {
			example.observe('click', this.showAutocomplete.bind(this, example.innerHTML.unescapeHTML()));
		}.bind(this));

		this.domForm.observe('submit', function(event) {event.stop()}.bindAsEventListener(this)); //prevent form submit
		this.domForm.fire('popup:update');
	},

	showAutocomplete: function(value)
	{
		if (value != undefined)
			this.domTextbox.value = value;

		//hack to make autocompleter send empty request, which will return popular models

		this.domTextbox.focus();

		if(this.autocompleter.observer) clearTimeout(this.autocompleter.observer);
		this.autocompleter.observer = setTimeout(function() {
			this.domTextbox.focus(); //to be sure
			this.autocompleter.activate();
		}.bind(this), this.autocompleter.options.frequency*1000);
	},

	showPopular: function(event)
	{
		this.showAutocomplete("");
	},


	onAutocompleterUpdate: function(domLi)
	{
		this.domModelIdInput.value=domLi.readAttribute('model_id');
		this.domForm.request({onSuccess: function (res) {this.domForm.replace(res.responseText)}.bind(this)});
	}
});



var DeviceConfirmDialog = Class.create({
	initialize: function(form)
	{
		this.domForm = $(form);
		this.domForm.fire('popup:update');

		this.domChangeDevice = this.domForm.down('.change-device');

		this.domChangeDevice.observe('click', this.onChangeDeviceClick.bindAsEventListener(this));
	},

	onChangeDeviceClick: function(event)
	{
			event.stop();

			new Ajax.Request(this.domChangeDevice.href, {
				onSuccess: function(res) {
					this.domForm.replace(res.responseText);
				}.bind(this)
			});
	}

});


function setLang(url) {
	window.location.href= url;
}






var LangSelect = Class.create({

	initialize: function(element)
	{
		//return;
		this.domContainer = $(element);


		//create popup part and add all links there
		this.domPopup = new Element('div', {'class': 'select-popup', style: 'display: none;'});
		this.domContainer.appendChild(this.domPopup);

		this.domContainer.select('a').each(function(link) {
			link.writeAttribute('original_text', link.down('span.locale-name').innerHTML.unescapeHTML());
			this.domPopup.appendChild(link);
		}.bind(this));


		//create textbox to show the current selection
		this.domFlag = new Element('span', {'class': 'flag'});
		this.domContainer.appendChild(this.domFlag);

		this.domTextbox = new Element('input', {type: 'text', 'class': 'select-textbox'});
		this.domContainer.appendChild(this.domTextbox);

		//ensure that we have active link
		if (!this.domPopup.down('a.selected'))
			this.domPopup.down('a').addClassName('selected');





		this.domContainer.observe('click', this.onContainerClick.bindAsEventListener(this));

		this.domPopup.observe('scroll', this.onPopupScroll.bindAsEventListener(this));

		this.domTextbox.observe('focus', this.onTextboxFocus.bindAsEventListener(this));
		this.domTextbox.observe('blur', this.onTextboxBlur.bindAsEventListener(this));
		this.domTextbox.observe('keyup', this.onTextboxKeyUp.bindAsEventListener(this));
		this.domTextbox.observe('keydown', this.onTextboxKeyDown.bindAsEventListener(this));

		this.domPopup.select('a').each(function(link) {
			link.observe('click', this.onLinkClick.bindAsEventListener(this, link));
		}.bind(this));


		this.setSelection();
	},


	setSelection: function()
	{
		var domLink = this.domPopup.down('a.selected');


		this.domTextbox.value = domLink.readAttribute('original_text');
		this.domFlag.className = domLink.down('.flag').className;

	},

	onContainerClick: function(event)
	{
		this.domTextbox.focus();
	},

	onPopupScroll: function()
	{
		this.domTextbox.focus();
	},

	showPopup: function()
	{
		this.domPopup.show();

		//set the focus
		var selected_link = this.domPopup.down('a[class~=selected]');
		this.domPopup.select('a').invoke('removeClassName', 'focus');
		if (selected_link)
		{
			selected_link.addClassName('focus');
			this.domPopup.scrollTop = selected_link.offsetTop;
		}

		this.filter("");
	},


	onTextboxFocus: function(event)
	{
		clearTimeout(this.close_timer);
		if (!this.domPopup.visible())
		{
			this.domTextbox.value = '';
			this.showPopup();
		}
	},

	onTextboxBlur: function(event)
	{
		//delay popup closing a bit since, to ensure that link click works fine
		this.close_timer = setTimeout(function() {
			this.setSelection();
			this.domPopup.hide();
		}.bind(this), 200);
	},

	onTextboxKeyUp: function(event)
	{

		this.filter(this.domTextbox.value);
	},

	onLinkClick: function(event, link)
	{
		if (event)
			event.stop();


		if (link)
		{
			this.domPopup.select('a').invoke('removeClassName', 'selected');
			link.addClassName('selected');
			setTimeout(function() {document.location.href=link.readAttribute('lang_href')}, 500);

			this.setSelection();
			this.domPopup.hide();
		}


	},


	onTextboxKeyDown: function(event)
	{
		var code = event.keyCode;

		switch (code) {
		case 38: //up
			this.moveUp();
			break;

		case 40: //down
			this.moveDown();
			break;

		case 13: //enter
			this.onEnter();
			break;

		case 27: //esc
			this.onEsc();
			break;
		}
	},


	filter: function(text)
	{
		text = text.toLowerCase();

		var regexp = new RegExp(text.replace(/[^a-z0-9_-]/gi, ''), "i");
		var m;



		this.domPopup.select('a').each(function(link) {
			var original_text = link.readAttribute('original_text');

			if (text == '')
			{
				link.show();
				link.down('span.locale-name').innerHTML = original_text.escapeHTML();
			}
			else if (m = original_text.match(regexp))
			{
				link.down('span.locale-name').innerHTML = original_text.replace(regexp, '<strong>'+m[0]+'</strong>').replace(/&/g, '&amp;');
				link.show();
			}
			else
			{
				link.hide();
			}

		});

	},

	moveUp: function()
	{
		var links = this.domPopup.select('a');
		var res;

		//find first visible link after first focused and visble link
		var found_current = false;
		for (var i = links.length-1; i >= 0; i--)
		{
			if (links[i].visible() && links[i].hasClassName('focus'))
			{
				found_current = true;
				continue;
			}

			if (found_current && links[i].visible())
			{
				res = links[i];
				break;
			}

		}


		links.invoke('removeClassName', 'focus');
		if (res)
		{
			res.addClassName('focus');
			this.domPopup.scrollTop = res.offsetTop;
		}
	},

	moveDown: function()
	{
		var links = this.domPopup.select('a');

		var res;

		//find first visible link after first focused and visble link
		var found_current = false;
		for (var i = 0; i < links.length; i++)
		{
			if (links[i].visible() && links[i].hasClassName('focus'))
			{
				found_current = true;
				continue;
			}

			if (found_current && links[i].visible())
			{
				res = links[i];
				break;
			}

		}

		//find first visible link
		if (!res && !found_current)
		{
			for (var i = 0; i < links.length; i++)
			{
				if (links[i].visible())
				{
					res = links[i];
					break;
				}
			}
		}


		if (res)
		{
			links.invoke('removeClassName', 'focus');
			res.addClassName('focus');

			this.domPopup.scrollTop = res.offsetTop;
		}
	},


	onEnter: function()
	{
		var links = this.domPopup.select('a');

		var res = null;

		//find visible and focused link
		var found_current = false;
		for (var i = 0; i < links.length; i++)
		{
			if (links[i].visible() && links[i].hasClassName('focus'))
			{
				res = links[i];
				break;
			}
		}


		this.onLinkClick(null, res);
	},


	onEsc: function()
	{
		this.domTextbox.blur();
	}


});




var SmartHoverMenu = Class.create({

	initialize: function(container, currentClassName)
	{
		this.domContainer = $(container);
		this.currentClassName = currentClassName || 'current';


		this.domDefaultLink = this.getCurrentLink();

		this.onMouseOverBound = this.onMouseOver.bindAsEventListener(this);
		this.onMouseOutBound = this.onMouseOut.bindAsEventListener(this);
		this.onMouseOutDelayedBound = this.onMouseOutDelayed.bind(this);

		var links = this.domContainer.select('a');
		for (var i = 0; i < links.length; i++)
		{
			links[i].observe('mouseover', this.onMouseOverBound);
			links[i].observe('mouseout', this.onMouseOutBound);
		}

	},


	getCurrentLink: function()
	{
		return this.domContainer.down('a.'+this.currentClassName);
	},

	setCurrentLink: function(domLink)
	{
		var old = this.getCurrentLink();
		if (old)
			old.removeClassName(this.currentClassName);

		if (domLink)
			domLink.addClassName(this.currentClassName);
	},

	onMouseOver: function(event)
	{
		clearTimeout(this.mouseOutTimer);

		var domLink = event.findElement('a');
		this.setCurrentLink(domLink);
	},

	onMouseOut: function(event)
	{
		this.mouseOutTimer = setTimeout(this.onMouseOutDelayedBound, 300);
	},

	onMouseOutDelayed: function()
	{
		this.setCurrentLink(this.domDefaultLink);
	}

});




function Set_Cookie( name, value, expires, path, domain, secure )
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}


function Get_Cookie( check_name )
{
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for ( i = 0; i < a_all_cookies.length; i++ )
    {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split( '=' );


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if ( cookie_name == check_name )
        {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if ( a_temp_cookie.length > 1 )
            {
                cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if ( !b_cookie_found )
    {
        return null;
    }
}


// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
if ( Get_Cookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


function addPseudoClasses()
{
    //add last child classes somewhere
    $$('.p_pager:last-child', '.cont .pd-block:last-child', '#leftCol .cont:last-child', '#rightCol .cont:last-child').each(function(e) {
    	var classNames = e.className.split(' ');
    	var len = classNames.length;
    	for (var i = 0; i < len; i++)
    	{
    		classNames.push(classNames[i]+'-last-child');
    	}

    	classNames.push('last-child');
    	e.className = classNames.join(' ');
    });

    $$('.cont .pd-block:empty').each(function(e) {
    	var classNames = e.className.split(' ');
    	var len = classNames.length;
    	for (var i = 0; i < len; i++)
    	{
    		classNames.push(classNames[i]+'-empty');
    	}

    	classNames.push('empty');
    	e.className = classNames.join(' ');
    });

}

document.observe('dom:loaded', fixSidebarBlocksSizes);
Event.observe(window, 'load', fixSidebarBlocksSizes); //to be sure ;)

document.observe('dom:loaded', addPseudoClasses);


Init = function (){
    addAutoComplete();    
}

Event.observe(window, 'load', Init);


