function openPage(button, url) {
	button.onclick = 'void(0)';
	window.location.href=url;
}




/* loginForm functions*/


function forgotPassword(){
    document.getElementById('forgot').checked = true;
    document.getElementById('loginForm').submit();
}

function toggleRegister(status) {
    switch (status) {
		case 0:
            document.getElementById('register').style.display = 'none';
            $$('#loginForm input#pwd').first().setStyle({ display: 'block'  });
        break;
        case 1:
            document.getElementById('register').style.display = 'none';
            $$('#loginForm input#pwd').first().setStyle({ display: 'none'  });
        break;
        case 2:
            document.getElementById('register').style.display = 'block';
            $$('#loginForm input#pwd').first().setStyle({ display: 'none'  });
        break;
		default:
            document.getElementById('register').style.display = 'none';
            $$('#loginForm input#pwd').first().setStyle({ display: 'block'  });
		break;
    }





}
/*
window.onload = function (){
    toggleRegister(document.getElementById('registerToggle').checked);
}

*/

function LoginValidate(){
    var error = '';
    var confirm_password = document.getElementById('confirm_password').value;
    var password = document.getElementById('new_password').value;

    if (!document.getElementById('email').value) {
        error += __('Please enter your email') + "\n";
    }
    if (document.getElementById('registerToggle').checked) {

        if (!document.getElementById('name').value) {
            error += __('Please enter your full name') + "\n";
        }
        if (!password) {
            error += __('Please enter your new password') + "\n";
        } else if (password.length < 1) {
            error += __('Password should be more than 1 char') + "\n";
        } else if (!password.match(/^[\w\d\.\@\#\$\%\^\&\*\(\)\!\\\/]+$/)) {
            error += __('Password should contain only English chars') + "\n";
        }

        if (!confirm_password) {
            error += __('Please confirm your password') + "\n";
        } else if (confirm_password != password) {
            error += __('Password do not match confirmation') + "\n";
        }

        if (!document.getElementById('countries').value) {
            error += __('Please enter country') + "\n";
        }
        /*
        if (!document.getElementById('model').value) {
            error += __('Please enter your model') + "\n";
        }
        */
    }
    if (error) {
        alert(error);
        return false;
    }
    return true;
}

var Popup = Class.create({
    initialize: function(options)
    {
        //$$('.popup').each(function(e) {e.fire('popup:close')});


        this.options = options;
        this.initDom();

        if (this.domBody.getHeight() < 100)
        {
            this.domBody.style.paddingTop = '30px'
            this.domBody.style.paddingBottom = '30px'
        }

        this.center();
    },

    initDom: function()
    {
        try {

        this.domPopup = new Element('div', {'class': 'popup'});

        /*table workaround*/
        var domTable = new Element('table', {cellspacing: '0', cellpadding: '0', border: '0'}); this.domPopup.appendChild(domTable);
        var domTbody = new Element('tbody'); domTable.appendChild(domTbody);
        var domRow = new Element('tr'); domTbody.appendChild(domRow);
        var domCell = new Element('td'); domRow.appendChild(domCell);


        this.domHeader = new Element('div', {'class': 'p_header'});
        domCell.appendChild(this.domHeader);


        this.domCloseLink = new Element('a', {href:'javascript:void(0)', 'class':'p_close'});
        this.domCloseLink.innerHTML = __('CLOSE');
        this.domHeader.appendChild(this.domCloseLink);

        this.domTitle = new Element('span', {'class':'p_title'});
        this.domTitle.update(this.options.title || 'Popup');
        this.domHeader.appendChild(this.domTitle);

        this.domBody = new Element('div', {'class': 'p_body'});
        domCell.appendChild(this.domBody);


        if (this.options.html)
            this.domBody.innerHTML = this.options.html; //prevent evaling scripts



        this.domOverlay = new Element('div', {'class': 'roverlay'});


        /*workaround to get body height*/

        var domTmp = new Element('div');
        document.body.appendChild(domTmp);
        var tmpOffset = domTmp.cumulativeOffset();
        domTmp.remove();

        /*workaround to get body height |end */
        this.domOverlay.style.height = tmpOffset.top+'px';


        $(document.body).appendChild(this.domOverlay);
        $(document.body).appendChild(this.domPopup);



        this.domCloseLink.observe('click', this.close.bind(this));
        this.domOverlay.observe('click', this.close.bind(this));
        this.domPopup.observe('popup:close', this.close.bind(this));
        }
        catch (e) {console.log(e)}
    },


    center: function()
    {
        var viewportSize = document.viewport.getDimensions();

        /* fix the vertical dimension */
        /*
        var domTmp = new Element('div', {style: 'position: absolute; left: 0; top: 0; width: 100%; height: 100%; margin: 0; padding: 0; border: none;'});
        document.body.appendChild(domTmp);
        viewportSize.height = domTmp.getHeight();
        viewportSize.width = domTmp.getWidth();
        domTmp.remove();
        */
        /* fix the vertical dimension |end */



        var popupSize = this.domPopup.getDimensions();




        var targetViewportOffset = [(viewportSize.width-popupSize.width)/2, (viewportSize.height-popupSize.height)/2];
        var currentViewportOffset = this.domPopup.viewportOffset();

        var currentDocumentOffset = this.domPopup.cumulativeOffset();
        var targetDocumentOffset = [
        targetViewportOffset[0]-currentViewportOffset[0]+currentDocumentOffset[0],
        targetViewportOffset[1]-currentViewportOffset[1]+currentDocumentOffset[1]
        ];


        var styleLeft = targetDocumentOffset[0]+'px';
        var styleTop = targetDocumentOffset[1]+'px';


        this.domPopup.style.left = styleLeft;
        this.domPopup.style.top = styleTop;
    },



    close: function()
    {
        this.domPopup.remove();
        this.domOverlay.remove();
    }
});







var ajaxLogin = Class.create({
    initialize: function(returl) {
        this.returl = returl;
        this.showLoginPopup();
    },

    // AJAX FUNCTION ////////////////////////////////////////////////////
    showLoginPopup: function() {
        var url = '/' + COUNTRY + '/login';

            new Ajax.Request(url, //var myAjax =
                {
                    method: 'post',
                    parameters:  {'returl': this.returl},  //  pars,
                    onComplete: this.showResponse.bind(this)
                    //onFailure: function() { console.log(arguments) },
                    //onException: function() { console.log(arguments) },
                    //onSuccess: function(transport) {
                    //    if (transport.responseText.match(/href="http:\/\/prototypejs.org/))
                    //      $('notice').update('Yes').setStyle({ background: '#dfd' });
                    //    else
                    //      $('notice').update('No').setStyle({ background: '#fdd' });
                    //}

                });
            return true;
    },


    showResponse: function(originalRequest) {
        if(originalRequest.headerJSON && originalRequest.headerJSON['type'] == 'form') {
            var title= originalRequest.headerJSON['title'];
            new Popup({'html': originalRequest.responseText, 'title': title});

        }
    }

});

/////////////////////////////////////////////////////////////////////////////////////////////


var ajaxSupportForm = Class.create({
	initialize: function(returl) {
	    this.returl = returl;
	    this.showSupportFormPopup();
	},

	showSupportFormPopup: function() {
		var url = '/' + COUNTRY + '/support';

		new Ajax.Request(url, //var myAjax =
		{
			method: 'post',
            parameters:  {'returl': this.returl},  //  pars,
            onComplete: this.showResponse.bind(this)
		});
		return true;
	},

    showResponse: function(originalRequest) {
        if(originalRequest.headerJSON && originalRequest.headerJSON['type'] == 'form') {
            var title= originalRequest.headerJSON['title'];
            new Popup({'html': originalRequest.responseText, 'title': title});

        }
    }

});




var Rainbow = Class.create({

	initialize: function()
	{
		//settings
		this.effectDuration = 0.3;


		this.rainbow = $('rainbow');
		this.items = $$('#rainbow > li');



		this.rainbow.observe('mouseover', this.onMouseOverGlobal.bindAsEventListener(this));
		this.rainbow.observe('mouseout', this.onMouseOutGlobal.bindAsEventListener(this));


		var maxheight = 0;

		for (var i = 0; i < this.items.length; i++)
		{
			this.items[i].observe('mouseover', this.onMouseOver.bindAsEventListener(this, this.items[i]));

			var domUl = this.items[i].down('ul');
			if (domUl)
			{
			     var height =  domUl.getHeight();
			     if (height > maxheight)
				    maxheight = height;
			}

		}


		/*
		//uncomment this code to make all submenus the same height
		for (var i = 0; i < this.items.length; i++)
		{
			this.items[i].down('ul').style.height = maxheight+'px'
		}
		*/


		for (var i = 0; i < this.items.length; i++)
		{
			if (this.items[i].down('ul') && this.items[i].down('ul').visible())
			{
				this.defaultItem = this.items[i];
				break;
			}
		}





		$('title').observe('mouseover', this.onMouseOver.bindAsEventListener(this, this.defaultItem));



	},

	onMouseOver: function(event, item)
	{
		clearTimeout(this.expandTeimer);
		this.expandTeimer = setTimeout(this.expandItem.bind(this, item), 500);
	},


	expandItem: function(item, force)
	{
		if (!force && this.hideEffect && this.hideEffect.state != 'finished')
			return;

		if (!force && this.showEffect && this.showEffect.state != 'finished')
			return;


		if (item && item.down('ul') && item.down('ul').visible())
			return;


		//collapse all expanded ones
		for (var i = 0; i < this.items.length; i++)
		{
			if (this.items[i] == item)
				continue;

			var ul = this.items[i].down('ul');


			if (!ul)
			 continue;

			if (!ul.visible())
				continue;


			this.hideEffect = new Effect.BlindUp(ul, {
				duration: this.effectDuration
			});
		}




	   if (item && item.down('ul'))
	   {
	       this.showEffect = new Effect.BlindDown(item.down('ul'), {
		    duration: this.effectDuration
	       });
	   }




	},

	onMouseOverGlobal: function(event)
	{
        if (this.inactivityTimer)
            clearTimeout(this.inactivityTimer);
	},

	onMouseOutGlobal: function(event)
	{
	    if (!this.onInactivityBound)
	       this.onInactivityBound = this.onInactivity.bind(this);

	    setTimeout(this.onInactivityBound, 2000);
	},

	onInactivity: function()
	{
	    //this.expandItem(this.defaultItem, true);
	    //do nothing
	}

});



var inputText = Class.create({
	initialize: function(element, text)
	{
		this.element = element;
		this.text = text;
		this.element.value = this.text;
		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;
		}
	}
});

/////////////////////////////////////////////////////////////////////////////////////////////


/* Main function to chance language*/
function LanguageChange(elem) {
    window.location.href = '/'+elem.value + window.location.pathname + window.location.search;
}


var functionsList = new Array();

/* Main function to run everything*/
Init = function () {
    $$('div.starContainer').each(  function(element, i) {
            new Rating (element) ;
       }
    );
    new Lightbox();


    if( window.popupsList )
    for(i=0; i< popupsList.length; i++ ) {
        new Popup({html: popupsList[i]['content'], title: popupsList[i]['title'] })


    }
    if (window.functionsList)
    for(i=0; i< window.functionsList.length; i++ ) {
    	window.functionsList[i]();


    }

}

window.onload = Init;

