/**
 * 2Fresh
 *
 * Base Class
 *
 */
MooTools.lang.setLanguage('cs-CZ');

var TwoFresh = {
    'version' : '1.0',
	'verbose' : false  // nastavuje zdali to ma byt ukecane ...
}

var FF = function(){};

FF.Log = new Class({
	enable : false,

	initialize : function (){

		if (TwoFresh.verbose){
			try {
				if (console.log || window.firebug) {
					console.log('-- Firebug Enable --');
					this.enable = true;
				}
			}catch(e) {}
		}

	},

	write: function (){
		if (this.enable) {
			if (arguments.length > 2 ){
				console.log(arguments);
			}else if (arguments.length == 2 ){
				console.log(arguments[0],arguments[1]);
			}else {
				console.log(arguments[0]);
			}


		}
	}
});

// Base Instance
var Log = {};
window.addEvent('domready', function() {
	Log = new FF.Log();
});


FF.Page = new Class({

	initialize: function (){
		// set brosers css
		if (Browser.Engine.trident){
		  $$('body')[0].addClass('ie');
		}

		this.initVote();
		this.initError();
	},

	initVote: function (){
		if ($('dialog-vote')){
			this.boxVote = $('dialog-vote');


			$('btn-voteClose').addEvent('click', function(e) {
				e.stop();
				this.boxVote.addClass('no');
			}.bind(this));



			this.boxVote.addEvent('click', function(e) {
				e.stop();
				this.boxVote.addClass('no');
			}.bind(this));

			this.boxVote.getChildren('.dialogInner')[0].addEvent('click', function(e) {
				e.stop();
			});


			$('btn-vote_now').addEvent('click', function(e) {
				e.stop();

				//alert($('system_captcha_vote').get('value'))
				postData = $H({'station_refresh_id' : id ,
							  'system_captcha' : $('system_captcha_vote').get('value')
							  });

				try { pageTracker._trackPageview('/virtualPage/vote-captcha'); } catch (e) {}

				new FF.JSON({
						'url' : baseUrl + 'a/stationRefreshVote/create',
						'onTrue' : function(JSONobject){
										Page.showVoteThanks();
										this.boxVote.addClass('no');
										}.bind(this),
						'onFalse' : function(JSONobject){
										Page.showErrorMessage(JSONobject.msg);
										this.boxVote.addClass('no');

						}.bind(this)

				}).send( postData.toQueryString() );
			}.bind(this));


			// dame ho projistotu nazacatek
			$$('body')[0].grab(this.boxVote,'top');
			$('helpRefreshCaptcha').set('src',$('helpRefreshCaptcha').get('src')+'?&noCache=' + new Date().getTime() );

		}
	},

	initError: function (){
		this.boxError = $('dialog-error');

		$('btn-errorClose').addEvent('click', function(e) {
			e.stop();
			this.boxError.addClass('no');
		}.bind(this));


		$('btn-errorContinue').addEvent('click', function(e) {
			e.stop();
			this.boxError.addClass('no');
		}.bind(this));

		this.boxError.addEvent('click', function(e) {
            e.stop();
            this.boxError.addClass('no');
        }.bind(this));

		this.boxError.getChildren('.dialogInner')[0].addEvent('click', function(e) {
            e.stop();
        });

		// dame ho projistotu nazacatek
		$$('body')[0].grab(this.boxError,'top');

	},

	showVote: function (id, tit){

		$('system_captcha_vote').set('value','');
		$('helpRefreshCaptcha').set('src',$('helpRefreshCaptcha').get('src')+'?&noCache=' + new Date().getTime() );

		try { pageTracker._trackPageview('/virtualPage/vote-popup'); } catch (e) {}
		this.boxVote.removeClass('no');



	},

	showVoteThanks: function (id, tit){

		var voteBox = new Elements.from('<div class="box-vote"><div class="wrapper">&nbsp;</div></div>');

		voteBox.addEvent('slowhide', function() {
			voteBox.tween('opacity', [1, 0]);
		});


		$$('body')[0].adopt(voteBox);
		voteBox.tween('opacity', [0, 1]);

		// hide ...

		(function(){ voteBox.fireEvent('slowhide') }).delay(2000);
	},

	showEmailThanks: function (id, tit){
		var mBox = new Elements.from('<div class="box-okmail"><div class="wrapper">&nbsp;</div></div>');

		mBox.addEvent('slowhide', function() {
			mBox.tween('opacity', [1, 0]);
		});
		$$('body')[0].adopt(mBox);
		mBox.tween('opacity', [0, 1]);
		// hide ...
		(function(){ mBox.fireEvent('slowhide') }).delay(2000);
	},


	actionVote : function (id, tit){
		if (UserIsLoged){
			postData = $H({'station_refresh_id' : id });

			try { pageTracker._trackPageview('/virtualPage/vote-registred'); } catch (e) {}

			new FF.JSON({
					'url' : baseUrl + 'a/stationRefreshVote/create',
					'onTrue' : function(JSONobject){
									Page.showVoteThanks(id, tit);
									},
					'onFalse' : function(JSONobject){
									Page.showErrorMessage(JSONobject.msg);

					}

			}).send( postData.toQueryString() );
		} else {
			this.showVote(id, tit);
		}
	},

	showErrorMessage: function (message, add_Class){
		this.boxError.getChildren('div')[0].getChildren('div.cont')[0].getChildren('p').set('text',message);
		this.boxError.removeClass('no');
	},


	showLoading: function (inElement){
		var loadingBox = new Elements.from('<div class="box-loading"><div class="wrapper">&nbsp;</div></div>');

		loadingBox.addEvent('slowhide', function() {
			loadingBox.tween('opacity', [1, 0]);
		});

		if ($defined(inElement)){
			inElement.setStyle('position','relative');
			loadingBox.setStyle('position','absolute');
			// TODO : Dopracovat myslenku
			$(inElement)[0].adopt(loadingBox);
		}else {
			$$('body')[0].adopt(loadingBox);
			loadingBox.tween('opacity', [0, 1]);
		}
		return loadingBox;
	},

	sendEmailToFriend : function (){
		// send Email
		new FF.JSON({
					'url' : baseUrl + 'a/user/sendMailFromPage',
					'onTrue' : function(JSONobject){
									//
									$('dialog-sendMessage').addClass('no');
									Page.showEmailThanks();
					},
					'onFalse' : function (JSONobject){
						Page.showErrorMessage(JSONobject.msg);
					}
		}).send($('form-sendMessage'));
		return false;

	},


    refresh : function()
    {
        new URI(FF_Page_CurrentUrl).go()
    },

	redirect : function(Url)
    {
        new URI(Url).go()
    },

	login : function (){
		// login
		new FF.JSON({
					'url' : baseUrl + 'a/user/login',
					'onTrue' : function(JSONobject){
									Page.redirect(JSONobject.data.url);
									// Page.refresh();
									},
					'onFalse' : function (JSONobject){
						switch(JSONobject.code)
						{
							case 202:
								eleShake = $('box-signIn').getChildren('div')[0];
								eleShake.set('shake', {times: 4, duration: 600});
								eleShake.shake('left', 20);

								header = eleShake.getChildren('.header')[0];
								headerContent = header.get('text');
								header.set('text',JSONobject.msg);
								header.addClass('hlp_wrong');

								wrongElement = $('login_form').getChildren('p').getChildren('input[type!=submit]');

								wrongElement.each(function(item, index) {
									item.addClass('validation-failed')
								}, this);


								var backToNormal = function(){
									this.ele.removeClass('hlp_wrong');
									this.ele.set('text', this.text);
								};
								backToNormal.delay(3000, $H({'ele': header, 'text': headerContent})); //Alerts: 'moo! Element id is: ... '



								break;
							default:
								Page.showErrorMessage(JSONobject.msg);
						}
					}
		}).send($('login_form'));
		return false;
	},

	loginFB : function (){
		// Log.write('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF LOGIN');
		// login Facebook
		new FF.JSON({
					'url' : baseUrl + 'a/user/loginFB',
					'onTrue' : function(JSONobject){
									// Page.refresh();
									Page.redirect(JSONobject.data.url);
									},
					'onFalse' : function(JSONobject){
									switch(JSONobject.code)
                                    {
                                        case 502:
                                            // Uzivatel neni zatim registrovan
                                            Page.redirect('/zapoj-se');

                                            break;
										default:
											Page.showErrorMessage(JSONobject.msg);
                                    }
									}

		}).send();
		return false;
	},

	userConvertFB : function (){
		// Pridani Facebook Uctu k jiz existujici registraci
		new FF.JSON({
					'url' : baseUrl + 'a/user/convertToFB',
					'onTrue' : function(JSONobject){
									Page.refresh();
									},
					'onFalse' : function(JSONobject){
									Page.showErrorMessage(JSONobject.msg);
									}

		}).send();
		return false;
	},

	logout : function (){
		new FF.JSON({
				'url' : baseUrl+'a/user/logout',
				'onTrue' : function(JSONobject){
								Page.redirect('/');
								}
		}).send();
		return false;
	},
	logoutFB : function (){
		//FB.Connect.logout(function() {  Page.logout();  });
		FB.Connect.logout(function() {  Page.redirect('/');  });

		return false;
	}

});

// Base Instance
var Page = {};
window.addEvent('domready', function() {
	Page = new FF.Page();
});



FF.JSON = new Class({
	Extends: Request.JSON,

    /*
    onTrue
    onFalse ( JSONobject, errorMsg )
    onNotlogged
    */

    initialize: function(options){
        options.noCache = true;
        options.spiner = false;
		this.parent(options);
	},

    onNotLogged : function(){
        this.fireEvent('onNotlogged');
        Log.write('[2F] JSON : User not logged');
    },

    onStatusTrue : function (JSONobject){
        this.fireEvent('onTrue',[JSONobject]);
        Log.write('[2F] JSON Status OK');
    },

    onStatusFalse : function(JSONobject, errorMsg, errorCode){
        this.fireEvent('onFalse',[JSONobject, errorMsg]);
        Log.write('[2F] JSON Status False');
        Log.write('[2F] Error Code: '+ errorCode + ' / ' + errorMsg );
    },

    // zkopirovani z Request.JSON
    // TODO : .. mozna pozutt dedicnost?
    /**
     * zakladni nody
     ******
        {
            status: true,
            notLogged: true,
            redirectUrl : 'http://www.google.com',
            code: 102,
            msg: "chybova hlaska",
            data : {
                cokoli: 'dal'
            }
        }
     */
	success: function(text){
		this.response.json = JSON.decode(text, this.options.secure);

		Log.write(this.response.json);

		this.spiner.fireEvent('slowhide');
		//this.spiner.destroy();
        if ( $defined(this.response.json) && $defined(this.response.json.status) ){
            if ( this.response.json.status == true ){
            // status = true
                this.onStatusTrue(this.response.json || {});
            }else {
            // status = false
                if ($defined(this.response.json.redirectUrl) && this.response.json.redirectUrl != ''){
                // NUCENY REDIRECT
                    Page.redirect(this.response.json.redirectUrl);
                }else {
                    if ($defined(this.response.json.notLogged) && this.response.json.notLogged == true){
                    // notLogged
                        this.onNotLogged();
                    }else {
                    // otherError
                        if ($defined(this.response.json.code)){
                            if ($defined(this.response.json.msg)){
                                this.onStatusFalse(this.response.json, this.response.json.msg, this.response.json.code);
                            }else {
                                this.onStatusFalse(this.response.json, 'Error Code : ' + this.response.json.code);
                            }
                        }else {
                            // moc toho nevime...
                            this.onStatusFalse('Error in JSON communication');
                        }
                    }
                }
            }
        }


		this.onSuccess(this.response.json, text);
	},

    // TODO : KVULI  'ci_ajax_call':'1';
    send: function(options){
		this.spiner = Page.showLoading();

		if (!this.check(options)) return this;
		this.running = true;

		var type = $type(options);
		if (type == 'string' || type == 'element') options = {data: options};

		var old = this.options;
		options = $extend({data: old.data, url: old.url, method: old.method}, options);
		var data = options.data, url = String(options.url), method = options.method.toLowerCase();

		switch ($type(data)){
			case 'element': data = document.id(data).toQueryString(); break;
			case 'object': case 'hash': data = Hash.toQueryString(data);
		}

		if (this.options.format){
			var format = 'format=' + this.options.format;
			data = (data) ? format + '&' + data : format;
		}

		if (this.options.emulation && !['get', 'post'].contains(method)){
			var _method = '_method=' + method;
			data = (data) ? _method + '&' + data : _method;
			method = 'post';
		}

		if (this.options.urlEncoded && method == 'post'){
			var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : '';
			this.headers.set('Content-type', 'application/x-www-form-urlencoded' + encoding);
		}

		if (this.options.noCache){
			var noCache = 'noCache=' + new Date().getTime();
			data = (data) ? noCache + '&' + data : noCache;
		}

/**
 * @@@ Pridani prepinace pro CI
 *===============================================================================
 */
			var ciXHR = 'ci_ajax_call=1';
			data = (data) ? ciXHR + '&' + data : ciXHR;
/* /@@@  Pridani prepinace pro CI */


		var trimPosition = url.lastIndexOf('/');
		if (trimPosition > -1 && (trimPosition = url.indexOf('#')) > -1) url = url.substr(0, trimPosition);

		if (data && method == 'get'){
			url = url + (url.contains('?') ? '&' : '?') + data;
			data = null;
		}

		this.xhr.open(method.toUpperCase(), url, this.options.async);

		this.xhr.onreadystatechange = this.onStateChange.bind(this);

		this.headers.each(function(value, key){
			try {
				this.xhr.setRequestHeader(key, value);
			} catch (e){
				this.fireEvent('exception', [key, value]);
			}
		}, this);

		this.fireEvent('request');
		this.xhr.send(data);
		if (!this.options.async) this.onStateChange();
		return this;
	}

});
