// Bind function.
Function.prototype.bind = function(obj) {
  var method = this,
   temp = function() {
    return method.apply(obj, arguments);
   };
 
  return temp;
};

if(!console) {
	var console = {
		debug: function(whatwhat) {
		}
	}
};


var Dictatr = {
	
};


Dictatr.ModalOptions = {
	'background-color': '#000000',
	opacity: 0.3
}


Dictatr.User = function(onReady) {
			
	var that = this;
	$.getJSON("/user/get/format/json", function(response) {
		that.user = response.user;
		onReady();		
	});
		
};


Dictatr.User.prototype = {
		
	get: function() {
		return this.user;
	},
	
	
	update: function(onReady) {
		
		var that = this;
		$.getJSON("/user/get/format/json", function(response) {
			
			if(response.user.type >= 3 && that.user.type < 3) {
				// login
				$(document).trigger('dp:login')
			} else if(response.user.type < 3 && that.user.type >= 3) {
				// logout
				$(document).trigger('dp:logout');
			}
			
			that.user = response.user;
			onReady();		
		});
		
	}
	
	
};








Dictatr.Widget = { };


Dictatr.Widget.User = function(container) {
	
	this.container = $(container);
	
	  	
};

Dictatr.Widget.User.prototype = {
				
	render: function()
	{
		this.draw();		
	},
	
	
	draw: function() {
		
		var user = App.User.get();	
						
		switch(user.type.toString()) {
			
			case '0':
			var txt = '<strong>Kansanvihollinen</strong>, uhkaat kohtaloasi näyttämällä naamaasi täällä! <a href="/index/enemy-of-the-people" id="enemyOfThePeople">Minäkö? Miksi?</a>';
			this.container.html(txt);
			break;
			
			case '1':
		
			var callsign;
			if(user.secretname) {
				callsign = user.secretname;
			} else if(user.firstname) {
				callsign = user.firstname;
			}
			
			if(callsign) {
				var txt = 'Heil <strong>' + callsign + '</strong>! <form id="quickLogin"><input type="hidden" name="email" value="' + user.email + '" /><input type="text" name="password" /><button type="submit">Sisään</button></form><a href="/logout/clear">En ole ' + callsign + '</a>';
			} else {
				var txt = 'Tervehdys, <strong>siviili</strong>. <a href="/register">Haluan ihmisarvon! Liityn Puolueeseen!</a> | <a href="/login">Äpärä, etkö tunnista minua?</a>';
			}
			this.container.html(txt);
			
			if(callsign) {
				
				$("#quickLogin").submit(this.doLogin.bind(this));
			}
			
							
			break;
			
			case '2':
			var callsign;
			if(user.secretname) {
				callsign = user.secretname;
			} else if(user.firstname) {
				callsign = user.firstname;
			}
			var txt = 'Heil <strong>' + callsign + '</strong>! <form id="quickLogin"><input type="hidden" name="email" value="' + user.email + '" /><input type="password" name="password" /><button type="submit">Sisään</button></form><a href="/logout/clear">En ole ' + callsign + '</a>';
			this.container.html(txt);
			$("#quickLogin").submit(this.doLogin.bind(this));		
			break;
			
			default:
			var callsign;			
			if(user.secretname) {
				callsign = user.secretname;
			} else {
				callsign = user.firstname;
			}
			var txt = 'Heil <strong>' + callsign + '</strong>! <a href="/user/edit">Omat tiedot</a> | <a href="/logout">Kirjaudu ulos</a>';
			this.container.html(txt);
			break;
		}
				
			
		
	},
	
	
	doLogin: function() {
		
		var that = this;
		
		 $.ajax({
            type: "POST",
            url: "/login/handle/format/json",
            data: $('#quickLogin').serialize(),
            dataType: 'json',
            success: function(msg){
				App.User.update(function() {
					App.userWidget.render();
				});
            }
        });
		
		
		return false;

		
	}
	
	
	
		
};




Dictatr.Adi = function (interval, propability) {
    
    this.interval = interval;
    this.propability = propability; 
        
    $('#adi').mouseover(function() {
        $('#adi').css({ 'background-position': '0 146px' });
    });

    $('#adi').mouseout(function() {
        $('#adi').css({ 'background-position': '0 0' }); 
    });
		
    var x = setInterval(this.changeFace.bind(this), this.interval);
    
};

Dictatr.Adi.prototype = {
    
    interval: null,
    probability: null,
        
    changeFace: function() {
       var randomizer = ( Math.floor ( Math.random ( ) * 10 + 1 ) );
       if(randomizer > this.propability) {
           var attr = $('#adi').css('background-position');
		   var newAttr = (attr == '0px 146px') ? '0px 0px' : '0px 146px'; 
           $('#adi').css('background-position', newAttr);
        }
    }
};



Dictatr.Dictator = {
	
	
	getFullName: function(dictator) {
		
		if(!dictator.firstname)
			return dictator.lastname;
			
		if(dictator.name_reversed == '1') {
			return dictator.lastname + ' ' + dictator.firstname;
		} else {
			return dictator.firstname + ' ' + dictator.lastname;
		}
		
	}
	
	
	
};



Dictatr.Widget.Vote = function(config) {
	$.extend(this, config);
	this.init();
};

Dictatr.Widget.Vote.prototype = { 
	
	
	init: function()
	{
		this.id = this.element.id.split('-').pop();
		this.element.widget = this;
		
		$.getJSON('/article/get-vote/id/' + this.id + '/format/json', (function(response) {
						
			this.vote = response.vote;
			this.render(this);
			
		}).bind(this));
		
	},
		
	
	render: function() {
						
		if(this.vote.user_id) {
			$(this.element).empty().html('<div class="votebar votebar-l"><img class="article-vote-l article-vote-l-' + this.vote.average + '" src="/lib/images/pixel.gif" /></div><div class="vote-text">Kiitos äänestäsi. Yhteensä ' + this.vote.count + ' ääntä.</div>');
		} else {
						
			var elm = $('<div class="votebar votebar-l"><img class="star-l star-empty-l star-1" src="/lib/images/pixel.gif" /><img class="star-l star-empty-l star-2" src="/lib/images/pixel.gif" /><img class="star-l star-empty-l star-3" src="/lib/images/pixel.gif" /><img class="star-l star-empty-l star-4" src="/lib/images/pixel.gif" /><img class="star-l star-empty-l star-5" src="/lib/images/pixel.gif" /></div><div class="vote-text">Arvostele artikkeli</div>');			
						
			$(this.element).empty().append(elm);
			elm.get(0).widget = this;

			elm.listen('mouseout', '.star-l', function() {
				$(this).prevAll().add(this).removeClass('star-filled-l').addClass('star-empty-l');
			});
			
			elm.listen('mouseover', '.star-l', function() {
				$(this).prevAll().add(this).removeClass('star-empty-l').addClass('star-filled-l');
			});
			
			elm.listen('click', '.star-l', function() {
				
				var opinion = this.className.split(' ')[1].split('-')[1];
				var widget = $(this).parent().parent().get(0).widget; 
				$.getJSON('/article/vote/id/' + widget.id + '/opinion/' + opinion, function(response) {
					
					if(response.vote) {
						widget.vote = response.vote;
						widget.render();
					}
								
				});
				
				
								
				
								
			});
			
			
		}
		
		
		
		
		
		
		
				
	}
	
};


Dictatr.Widget.Voter = function(config) {
	$.extend(this, config);
	this.init();
};

Dictatr.Widget.Voter.prototype = { 
	
	
	init: function()
	{
		this.id = this.element.id.split('-').pop();
		this.element.widget = this;
		
		var elm = $(this.element);
		
		elm.listen('mouseout', '.star-l', function() {
			$(this).prevAll().add(this).removeClass('star-filled-l').addClass('star-empty-l');
		});
			
		elm.listen('mouseover', '.star-l', function() {
			$(this).prevAll().add(this).removeClass('star-empty-l').addClass('star-filled-l');
		});
			
		elm.listen('click', '.star-l', function() {
			
			var opinion = this.className.split(' ')[1].split('-')[1];
			var widget = $(this).parent().parent().get(0).widget; 
			$.getJSON('/article/vote/id/' + widget.id + '/opinion/' + opinion, function(response) {
				
				if(response.vote) {
					widget.vote = response.vote;
					widget.render();
				}
							
			});
				
								
		});

		
		
	},
		
	
	render: function() {
						
		if(this.vote.user_id) {
			$(this.element).empty().html('<div class="votebar votebar-l"><img class="article-vote-l article-vote-l-' + this.vote.average + '" src="/lib/images/pixel.gif" /></div><div class="vote-text">Kiitos äänestäsi. Yhteensä ' + this.vote.count + ' ääntä.</div>');
		} else {
			
			var elm = $('<div class="votebar votebar-l"><img class="star-l star-empty-l star-1" src="/lib/images/pixel.gif" /><img class="star-l star-empty-l star-2" src="/lib/images/pixel.gif" /><img class="star-l star-empty-l star-3" src="/lib/images/pixel.gif" /><img class="star-l star-empty-l star-4" src="/lib/images/pixel.gif" /><img class="star-l star-empty-l star-5" src="/lib/images/pixel.gif" /><div class="vote-text">Arvostele artikkeli</div></div>');			
						
			$(this.element).empty().append(elm);
			elm.get(0).widget = this;

			elm.listen('mouseout', '.star-l', function() {
				$(this).prevAll().add(this).removeClass('star-filled-l').addClass('star-empty-l');
			});
			
			elm.listen('mouseover', '.star-l', function() {
				$(this).prevAll().add(this).removeClass('star-empty-l').addClass('star-filled-l');
			});
			
			elm.listen('click', '.star-l', function() {
				
				var opinion = this.className.split(' ')[1].split('-')[1];
				var widget = $(this).parent().parent().get(0).widget; 
				$.getJSON('/article/vote/id/' + widget.id + '/opinion/' + opinion, function(response) {
					
					if(response.vote) {
						widget.vote = response.vote;
						widget.render();
					}
								
				});
				
				
								
				
								
			});
			
			
		}
		
		
		
		
		
		
		
				
	}
	
};



Dictatr.TinyMCE = {
	
	init: function(config)
	{
		var common = {
			theme : "advanced",
			convert_urls: true,
			relative_urls: false,
			content_css: "/lib/css/tinymce.css",
			language: 'fi',
			plugins: "table",
			theme_advanced_buttons2_add : "tablecontrols",
			button_tile_map: true,
			entity_encoding: 'raw',
			mode: 'textareas',
			editor_selector: 'mceEditor'
			
		};
		
		var returner = $.extend(common, config);
		return returner;
		
		
	}
	
	
};
