$.fn.removeStyle = function(style) {
	var search = new RegExp(style + '[^;]+;?', 'g');

	return this.each(function() {
		var $this = $(this);

		$this.attr('style',
			$this.attr('style').replace(search, '')
		);
	});
};

jQuery.fn.wallpaperGenerator = function(options) {
	this.settings = {
		generatorUrl: "http://micrositev5.eset.com/generator/",
		resolutions: {
			'0': {width: 1920, height: 1080}, // 16:9
			'1': {width: 1920, height: 1200}, // 16:10
			'2': {width: 1920, height: 1440}, // 4:3
			'3': {width: 1440, height: 900}, // 16:9
			'4': {width: 1680, height: 1050}, // 16:10
			'5': {width: 1600, height: 1200}, // 4:3
			'6': {width: 1366, height: 768}, // 16:9
			'7': {width: 1440, height: 900}, // 16:10
			'8': {width: 1400, height: 1050}, // 4:3
			'9': {width: 1280, height: 720}, // 16:9
			'10': {width: 1280, height: 800}, // 16:10
			'11': {width: 1280, height: 960}, // 4:3
			'12': {width: 1024, height: 768}, // 4:3
			'13': {width: 854, height: 480}, // 16:9
			'14': {width: 800, height: 600}, // 4:3
			'15': {width: 1280, height: 1024},
			'16': {width: 1152, height: 864},
			'17': {width: 1360, height: 768},
			'18': {width: 1650, height: 1050}
		},
		logoPositions: {
			'0': {x: 0.10, y: 0.10},
			'1': {x: 0.90, y: 0.10},
			'2': {x: 0.90, y: 0.90},
			'3': {x: 0.10, y: 0.90},
			'4': {x: 0.11, y: 0.10},
			'5': {x: 0.89, y: 0.10},
			'6': {x: 0.89, y: 0.90},
			'7': {x: 0.11, y: 0.90},
			'8': {x: 0.13, y: 0.10},
			'9': {x: 0.87, y: 0.10},
			'10': {x: 0.87, y: 0.90},
			'11': {x: 0.13, y: 0.90}		
		},
		files: {
			logo: {url: "http://s.esetsmartsecurity.com/assets/logo.png", width: 100, height: 50},
			background: {
				0: {url: "http://s.esetsmartsecurity.com/assets/bg01.jpg", width: 960, height: 600},
				1: {url: "http://s.esetsmartsecurity.com/assets/bg02.jpg", width: 960, height: 600},
				2: {url: "http://s.esetsmartsecurity.com/assets/bg03.jpg", width: 960, height: 600},
				3: {url: "http://s.esetsmartsecurity.com/assets/bg04.jpg", width: 960, height: 600}
			},
			android: {
				0: {url: "http://s.esetsmartsecurity.com/assets/android0.png", width: 400, height: 1000},
				1: {url: "http://s.esetsmartsecurity.com/assets/android1.png", width: 400, height: 1000},
				2: {url: "http://s.esetsmartsecurity.com/assets/android2.png", width: 400, height: 1000},
				3: {url: "http://s.esetsmartsecurity.com/assets/android3.png", width: 400, height: 440}
			}
		}
	};
	$.extend(this.settings, options);
	
	this.init = function() {
		_self = this;
		
		$(this.settings.area).append($('<img id="generator-bg" class="clickable" />').attr("src", this.settings.files.background[0].url));
		$(this.settings.area).append($('<img id="generator-android" class="clickable" />').attr("src", this.settings.files.android[0].url).attr("width", this.settings.files.android[0].width).attr("height", this.settings.files.android[0].height));
		$(this.settings.area).append($('<img id="generator-logo" class="clickable" />').attr("src", this.settings.files.logo.url).attr("width", this.settings.files.logo.width).attr("height", this.settings.files.logo.height));
		$(this.settings.area).append('<div id="generator-edge-left"></div><div id="generator-edge-right"></div>');
		$(this.settings.area).append('<div id="generator-overlay"><div class="dialog"></div></div>');

		this.widthSize = 960;
		this.heightSize = 540;
		this.edge = 0;
		this.resolution = 0;
		this.android = 0;
		this.resolution = 0;
		
		this.setBackground(0);
		this.setLogoSize(0.1);
		this.setLogoPosition(0);
		this.setAndroidSize(0.2);
		this.setAndroidPosition(0.5, 0.5);
		this.setResolution('1920x1080');

		$(this.settings.android).resizable({
			aspectRatio: true,
			handles: 'e, s, n, w, ne, se, sw, nw',
			minHeight: 100,
			resize: function(event, ui, t) {
				var h = (ui.originalSize.height-ui.size.height)/2;
				var w = (ui.originalSize.width-ui.size.width)/2;
				ui.position.top = ui.originalPosition.top+h;
				ui.position.left = ui.originalPosition.left+w;

				//ui.size.width = ui.size.width + ((ui.size.width - ui.originalSize.width)*2);
				//ui.size.height = ui.size.height + ((ui.size.height - ui.originalSize.height)*2);
			}
		}).parent().draggable({
			cursor: 'move',
			stop: function(event, ui) {
				_self.androidX = _self.getAndroidPosition().x;
				_self.androidY = _self.getAndroidPosition().y;
			}
		});
		$(this.settings.android).resizable("disable");
		$(".ui-state-disabled").css({opacity: 1});
		$(_self.settings.logo).disableSelection();
		
		$(this.settings.android).click(function() {
			$(_self.settings.android).resizable("enable");
			$(_self.settings.android).addClass("focus");
			$(_self.settings.logo).removeClass("focus");
			$(_self.settings.bg).removeClass("focus");
			$("#generator-edge-left, #generator-edge-right").removeClass("focus");
			_self.showAndroidOptions();
		});
		$(this.settings.logo).click(function() {
			$(_self.settings.android).resizable("disable");
			$(_self.settings.android).removeClass("focus");
			$(_self.settings.logo).addClass("focus");
			$(_self.settings.bg).removeClass("focus");
			$("#generator-edge-left, #generator-edge-right").removeClass("focus");
			_self.showLogoOptions();
		});
		$(this.settings.bg).click(function() {
			$(_self.settings.android).resizable("disable");
			$(_self.settings.android).removeClass("focus");
			$(_self.settings.logo).removeClass("focus");
			$(_self.settings.bg).addClass("focus");
			$("#generator-edge-left, #generator-edge-right").addClass("focus");
			_self.showBgOptions();
		});
		$(this.settings.android).parent().removeStyle('overflow');
	
		$(this.settings.button).live("click", this.download.bind(this));
		
		$(this).find("div.center").each(function() {
			$(this).width($(this).parent().outerWidth()+1).css({'margin': '0px auto'});
		});
		$("#changeResolution").click(this.showResolutionDialog.bind(this));
		$(this.settings.overlay).click(function() {
			$(_self.settings.overlay).find(".dialog").empty().removeClass("wizard");
			$(_self.settings.overlay).hide();
			$(this).unbind("click");
		});
		$(this.settings.overlay).find(".exit").live("click", function() {
			$(_self.settings.overlay).find(".dialog").empty().removeClass("wizard");
			$(_self.settings.overlay).hide();
		});
		
		// zobrazenie prvotneho wizardu
		var body = '<h2>' + $("#generator-dialog-wizard").attr("title") + '</h2>' + $("#generator-dialog-wizard").html();
		$(this.settings.overlay).find(".dialog").empty().append(body).addClass("wizard");
		$(this.settings.overlay).show();
		
		$("#mailTo").live("click", this.showMailDialog.bind(this));
		$("#startCreating ").live("click", function() {
			try { 
				 _gaq.push(['_trackEvent', 'Wallpaper', 'Start creating', 'language']);
			} catch(e) {};
		});
	}
	
	this.showBgOptions = function() {
		$(this.settings.options.bg).show();
		$(this.settings.options.logo).hide();
		$(this.settings.options.android).hide();
	}
	this.showLogoOptions = function() {
		$(this.settings.options.bg).hide();
		$(this.settings.options.logo).show();
		$(this.settings.options.android).hide();		
	}
	this.showAndroidOptions = function() {
		$(this.settings.options.bg).hide();
		$(this.settings.options.logo).hide();
		$(this.settings.options.android).show();		
	}
	this.showResolutionDialog = function(e) {
		var _self = this;
		e.preventDefault();

		var body = '<h2>' + $("#generator-dialog-resolution").attr("title") + '</h2>' + $("#generator-dialog-resolution").html() + '<span class="exit"></span>';
		$(this.settings.overlay).find(".dialog").empty().removeClass("wizard").append(body);
		$(this.settings.overlay).show();
		$(this.settings.overlay).find(".dialog a").click(function(e) {
			_self.setResolution($(this).text());
			$(this).parent().children('a').removeClass("current");
			$(this).addClass("current");
			$("#changeResolution").html('<span></span>' + $(this).text());
		});
		$(this.settings.overlay).find(".dialog a").filter(function(i) {
			return $(this).text() == $("#changeResolution").text();
		}).addClass("current");
	}
	this.showMailDialog = function(e) {
		var _self = this;
		e.preventDefault();

		var body = '<h2>' + $("#generator-dialog-mail").attr("title") + '</h2>' + $("#generator-dialog-mail").html() + '<span class="exit"></span>';
		$(this.settings.overlay).find(".dialog").empty().removeClass("wizard").append(body);
		$(this.settings.overlay).show();
		$(this.settings.overlay).find(".dialog input").val(_self.email);
		$(this.settings.overlay).find(".dialog .button2").click(function() {
			var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
			_self.email = $(_self.settings.overlay).find(".dialog input").val();
			if (reg.test(_self.email)) {
				$.post('mail.php', {to: _self.email, hash: _self.hash, locale: _self.settings.language}, function(data) {
					if (data.success = true) {
						try {_gaq.push(['_trackEvent', 'Wallpaper', 'Send wallpaper', _self.settings.language]);} catch (e) {};
						var body = '<h2>' + $("#generator-dialog-mailsuccess").attr("title") + '</h2>' + $("#generator-dialog-mailsuccess").html();
						$(_self.settings.overlay).find(".dialog").empty().append(body);
						$(_self.settings.overlay).find(".dialog .button").click(function() {
							$(_self.settings.overlay).find(".dialog").empty();
							$(_self.settings.overlay).hide();
						});
					} else {
						var body = '<h2>' + $("#generator-dialog-mailerror2").attr("title") + '</h2>' + $("#generator-dialog-mailerror2").html();
						$(_self.settings.overlay).find(".dialog").empty().append(body);
						$(_self.settings.overlay).find(".dialog .button").click(_self.showMailDialog.bind(_self));
					}
				}, "json");
			} else {
				var body = '<h2>' + $("#generator-dialog-mailerror1").attr("title") + '</h2>' + $("#generator-dialog-mailerror1").html();
				$(_self.settings.overlay).find(".dialog").empty().append(body);
				$(_self.settings.overlay).find(".dialog .button").click(_self.showMailDialog.bind(_self));
			}
		});
	}
	this.addFlip = function() {
		$(this.settings.android).css({
			'-moz-transform': 'scaleX(-1)',
			'-o-transform': 'scaleX(-1)',
			'-webkit-transform': 'scaleX(-1)',
			'transform': 'scaleX(-1)',
			'filter': 'FlipH',
			'-ms-filter': 'FlipH'
		});
	}
	this.removeFlip = function() {
		$(this.settings.android).css({
			'-moz-transform': 'none',
			'-o-transform': 'none',
			'-webkit-transform': 'none',
			'transform': 'none',
			'filter': 'none',
			'-ms-filter': '-ms-filter'
		});
	}
	
	// SETTERY
	this.setResolution = function(value) {
		var _self = this, resolution = value.split("x");
		var width = $(this.settings.area).width(), height = $(this.settings.area).height();
		var rate = resolution[1]/resolution[0];
		var edge = (width-(height/rate))/2;
		
		$("#generator-edge-left, #generator-edge-right").css({opacity: 0.9}).width(edge).show();
		this.edge = edge;
		this.widthSize = height/rate;
		
		$.each(this.settings.resolutions, function(i) {
			if (resolution[0] == this.width && resolution[1] == this.height) {
				_self.resolution = i;
			}
		});
		this.setLogoPosition(this.logoPosition);
	}
	this.setBackground = function(i, el) {
		$(el).parent().children().removeClass("current");
		$(el).addClass("current");
		this.background = i;
		$(this.settings.bg).attr("src", this.settings.files.background[i].url);
	}
	this.setAndroid = function(i, el) {
		$(el).parent().children().removeClass("current");
		$(el).addClass("current");
		this.android = i;
		
		if (i > 3) {
			this.addFlip();
			i = i%4;
		} else {
			this.removeFlip();
		}
		
		$(this.settings.android).attr("src", this.settings.files.android[i].url);
		var rate = this.settings.files.android[i].height/this.settings.files.android[i].width;
		if (rate != this.androidRate) {
			var width = $(this.settings.android).width();
			$(this.settings.android).height(width*rate);
			$(this.settings.android).parent(".ui-wrapper").height(width*rate+4);
		}
		this.androidRate = this.settings.files.android[i].height/this.settings.files.android[i].width;
	}
	this.setLogoSize = function(size) {
		this.logoSize = size;
		var ratio = this.getWidthSize(size) / $(this.settings.logo).width();
		$(this.settings.logo).width(this.getWidthSize(size));
		$(this.settings.logo).height($(this.settings.logo).height()*ratio);
	}
	this.setLogoPosition = function(position, el) {
		var resolution = this.settings.resolutions[this.resolution];
		var rate = resolution.height/resolution.width;

		if (rate == 0.625) {
			this.logoPosition = position%4 + 4;
			this.setLogoSize(0.112);
		} else if (rate == 0.75) {
			this.logoPosition = position%4 + 8;
			this.setLogoSize(0.133);
		} else {
			this.logoPosition = position%4;
			this.setLogoSize(0.1);
		}
		
		$(el).parent().children().removeClass("current");
		$(el).addClass("current");
		var position = this.settings.logoPositions[this.logoPosition];
		
		$(this.settings.logo).css({
			left: this.edge + this.getOffset($(this.settings.logo).width(), this.getWidthSize(position.x)),
			top: this.getOffset($(this.settings.logo).height(), this.getHeightSize(position.y))
		});
	}
	this.setAndroidSize = function(size) {
		this.androidSize = size;
		var ratio = this.getWidthSize(size) / $(this.settings.android).width();
	
		$(this.settings.android).width(this.getWidthSize(size));
		$(this.settings.android).height($(this.settings.android).height()*ratio);
		
		this.setAndroidPosition(this.androidX, this.androidY);
	}
	this.setAndroidPosition = function(x, y) {
		this.androidX = x;
		this.androidY = y;
		$(this.settings.android).css({
			left: this.getOffset($(this.settings.android).width(), this.getWidthSize(x)),
			top: this.getOffset($(this.settings.android).height(), this.getHeightSize(y))
		});
	}
	
	// GETTERY
	this.getWidth = function() {
		return this.widthSize;
	}
	this.getHeight = function() {
		return this.heightSize;
	}
	this.getWidthSize = function(percent) {
		return this.getWidth() * percent;
	}
	this.getHeightSize = function(percent) {
		return this.getHeight() * percent;
	}
	this.getWidthPercent = function(pixels) {
		return pixels / this.getWidth();
	}
	this.getHeightPercent = function(pixels) {
		return pixels / this.getHeight();
	}
	this.getOffset = function(size, offset) {
		return offset - (size/2);
	}
	this.getHalf = function(size) {
		return size/2;
	}
	this.getAndroidPosition = function() {
		var position = $(this.settings.android).parent().position();

		return {
			y: this.getHeightPercent(position.top + this.getHalf($(this.settings.android).height())),
			x: this.getWidthPercent(position.left - this.edge + this.getHalf($(this.settings.android).width()))
		};
	}
	this.getAndroidSize = function() {
		return this.getWidthPercent($(this.settings.android).width());
	}
	
	this.getRequest = function() {
		var url = "?";
		var params = {
			resolution: this.resolution,
			background: this.background,
			androidSize: this.getAndroidSize(),
			androidPositionX: this.getAndroidPosition().x,
			androidPositionY: this.getAndroidPosition().y,
			androidRotation: this.android,
			logoPosition: this.logoPosition,
			logoSize: this.logoSize
		};
		
		return params;
	}
	this.download = function(e) {
		e.preventDefault();
		var _self = this;
		$.get(this.settings.generatorUrl + 'add.php', this.getRequest(), function(data) {
			try {_gaq.push(['_trackEvent', 'Wallpaper', 'Generate wallpaper', _self.settings.language]);} catch (e) {};
			if (data.success == true) {
				_self.hash = data.hash;
				
				$("#downloadNow").attr("href", _self.settings.generatorUrl + "index.php?hash=" + _self.hash).live("click", function() {
					try {_gaq.push(['_trackEvent', 'Wallpaper', 'Save as', _self.settings.language]);} catch (e) {};
				});
				var body = '<h2>' + $("#generator-dialog-save").attr("title") + '</h2>' + $("#generator-dialog-save").html() + '<span class="exit"></span>';
				$(_self.settings.overlay).find(".dialog").empty().removeClass("wizard").append(body);
				$(_self.settings.overlay).show();
			} else {
				alert("Error in generator.")
			}
		}, "jsonp");
	}
	
	this.init();
	
    return this;
}

