/**
 * The "bind()" function extension from Prototype.js, extracted for general use
 *
 * @author Richard Harrison, http://www.pluggable.co.uk
 * @author Sam Stephenson (Modified from Prototype Javascript framework)
 * @license MIT-style license @see http://www.prototypejs.org/
 */
Function.prototype.bind = function()
{
    // http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Functions:arguments
    var _$A = function(a){return Array.prototype.slice.call(a);};

    if(arguments.length < 2 && (typeof arguments[0] == "undefined")) return this;

    var __method = this, args = _$A(arguments), object = args.shift();

    return function() {
      return __method.apply(object, args.concat(_$A(arguments)));
    };
};


Vykupto = {

	time : 0,

	timer : null,

	required : 0,

	ready : 0,

	message : {
		el : null,
		text : null,
		link : null
	},

	// konstanty pro typy vyskakovacich zprav
	MESSAGE_INFO : 'infoMessage',
	MESSAGE_ERROR : 'errorMessage',
	MESSAGE_SUCCESS : 'successMessage',


	/**
	 * Inicializace po nacteni stranky
	 */
	init : function()
	{
		// hezky selectbox
		$('#frmcityForm-city')
			.sSelect().change(function() {
				$('#topLogo').focus();
			})
			// kvuli IE6
			.css({
				position: 'absolute',
				top: '0px',
				left: '-10000px',
				display: 'block'
			})
		;

		// predvyplneny text v inputu na email
		$('.prefilledEmail')
			.focus(function() {
				if ($(this).hasClass('empty'))
				{
					this.value = '';
					$(this).removeClass('empty');
				}
			})
			.blur(function() {
				if ($.trim(this.value) == '')
				{
					this.value = 'Zadejte Váš e-mail';
					$(this).addClass('empty');
				}
			})
			.blur()
		;

		$('#topLogo').focus();

		// hover efekt pro odesilaci button
		$('#frmtopNewsletterForm-subscribe').hover(
			function() {
				$('#topEmailWrapper').addClass('hover');
			},
			function() {
				$('#topEmailWrapper').removeClass('hover');
			}
		);

	},


	/**
	 * Aktualizuje casovy udaj na titulce
	 */
	updateTime : function()
	{
		var minutes = parseInt(this.time / 60);
		var seconds = this.time % 60;
		var hours = parseInt(minutes / 60);
		minutes = minutes % 60;
		var days = parseInt(hours / 24);

                if (days > 3)
                {
                    hours = hours % 24;
                }
		if (minutes<10) minutes='0'+minutes;
		if (seconds<10) seconds='0'+seconds;

		$('#homeBoxTimeDaysCol').text(days);
		$('#homeBoxTimeHoursCol').text(hours);
		$('#homeBoxTimeMinutesCol').text(minutes);
		$('#homeBoxTimeSecondsCol').text(seconds);

		var daysTitle = this.inflect(days, 'dn\u016f', 'den', 'dny');
		$('#homeBoxTimeDaysTitle').text(daysTitle);

		var hoursTitle = this.inflect(hours, 'hodin', 'hodina', 'hodiny');
		$('#homeBoxTimeHoursTitle').text(hoursTitle);

		var minutesTitle = this.inflect(minutes, 'minut', 'minuta', 'minuty');
		$('#homeBoxTimeMinutesTitle').text(minutesTitle);

		var secondsTitle = this.inflect(seconds, 'vte\u0159in', 'vte\u0159ina', 'vte\u0159iny');
		$('#homeBoxTimeSecondsTitle').text(secondsTitle);


		if (days > 3)
		{
			$('#homeBoxTimeDaysCol').show();
			$('#homeBoxTimeDaysTitle').show();
			$('#homeBoxTimeLeft').show();
		}
		else
		{
			$('#homeBoxTimeDaysCol').hide();
			$('#homeBoxTimeDaysTitle').hide();
			$('#homeBoxTime').show();
		}

	},


	/**
	 * Provede sklonovani slova podle poctu
	 *
	 * @param value Pocet kusu
	 * @param normal Nekolik "kusu"
	 * @param one Jeden "kus"
	 * @param twoFour Dva/ctyri "kusy"
	 */
	inflect : function(value, normal, one, twoFour)
	{
		var result = normal;
		if (value == 1)
		{
			result = one;
		}
		else
		if (value > 1 && value < 5)
		{
			result = twoFour;
		}

		return result;
	},


	/**
	 * Spusti odpocet na titulce
	 */
	startCountdown : function()
	{
		if (this.time >= 0)
		{
			this.timer = window.setInterval(Vykupto.timeout.bind(this), 1000);
		}
	},


	/**
	 * Timeout na titulce
	 */
	timeout : function()
	{
		this.time--;
		if (this.time <= 0)
		{
			window.clearInterval(this.timer);
		}
		else
		{
			this.updateTime();
		}
	},


	/**
	 * Nastavi progresbar na titulce
	 */
	updateProgress : function()
	{
		var caretMin = 10;
		var caretMax = 170;

		var barMin = -4;
		var barMax = 164;

		var percentage = this.ready / this.required;
		if (percentage > 1)
		{
			percentage = 1;
		}

		var remaining = this.required - this.ready;
		if (remaining < 0)
		{
			remaining = 0;
		}

                var max_percentage = 0.75;
                if (percentage > max_percentage) percentage = max_percentage;

		var caretPos = parseInt(caretMin + ((caretMax - caretMin) * percentage))
		$('#homeBoxProgressCaret').css('left', caretPos + 'px');

		var barPos = parseInt(barMin + ((barMax - barMin) * percentage));
		$('#homeBoxProgressBarMask').css('left', barPos + 'px');

		$('#homeBoxReady').text(this.ready);
		$('#homeBoxRemaining').text(remaining);
		$('#homeBoxRequired').text(this.required);

		if (remaining == 0)
		{
			$('#homeBoxProgressDone').show();
		}

	},


	/**
	 * Inicializace titulky
	 */
	initHomepage : function()
	{
		Vykupto.updateTime();
		Vykupto.startCountdown();
		Vykupto.updateProgress();
	},


	/**
	 * Inicializace formularu
	 */
	initForm : function()
	{

		// focusovani inputu
		$('form .inputText input')
			.focus(function() {$(this).parent().addClass('focus');})
			.blur(function() {$(this).parent().removeClass('focus');})
		;

		// javascriptove ostylovani selectboxu
		$('form .inputSelect select').sSelect();

		// hover kvuli IE6
		$('.box button').hover(function() {$(this).addClass('hover');}, function() {$(this).removeClass('hover');});

	},


	/**
	 * Zobrazi zpravu systemu
	 *
	 * @param text Text zprávy
	 * @param type Vykupto.MESSAGE_INFO | Vykupto.MESSAGE_SUCCESS | Vykupto.MESSAGE_ERROR
	 */
	showMessage : function(text, type)
	{
		// pokud element nemame, tak ho vytvorime
		if (!this.message.el)
		{
			this.createMessage();
		}

		// nastavime text
		this.message.text.html(text);

		// nastavime tridu elementu a zobrazime ho
		this.message.el
			.attr('class', type)
			.show()
		;

	},


	/**
	 * Vytvori element pro zpravu systemu
	 */
	createMessage : function()
	{
		// odstavec textu
		this.message.text = $('<p />');

		// odkaz na zavreni
		this.message.link = $('<a />')
			.addClass('close')
			.text('Zav\u0159ít')
			.click(this.hideMessage.bind(this))
		;

		// samotna zprava
		this.message.el = $('<div />')
			.hide()
			.attr('id', 'messageBox')
			.append(this.message.text)
			.append(this.message.link)
			.prependTo($('#content'))
		;

	},


	/**
	 * Ukryje zpravu systemu
	 */
	hideMessage : function()
	{
		this.message.el.hide();
	},

        fbLogin : function(redirect_link)
        {
            Vykupto.showMessage('Provádím přihlášení pomocí Vašeho Facebook profilu, prosím vyčkejte...', 'successMessage');
            if (redirect_link)
                window.location = redirect_link;
            else
                window.location.reload();
            /*var myPermissions = "publish_stream"; // permissions your app needs
            FB.Connect.showPermissionDialog(myPermissions , function(perms) {
              if (!perms)
              {
                // handles if the user rejects the request for permissions. This is a good place to log off from Facebook connect
              }
              else
              {
                  // finish up here if the user has accepted permission request
              };
            });
            FB.ui(
               {
                 method: 'stream.publish',
                 message: 'getting educated about Facebook Connect',
                 attachment: {
                   name: 'Connect',
                   caption: 'The Facebook Connect JavaScript SDK',
                   description: (
                     'A small JavaScript library that allows you to harness ' +
                     'the power of Facebook, bringing the user\'s identity, ' +
                     'social graph and distribution power to your site.'
                   ),
                   href: 'http://github.com/facebook/connect-js'
                 },
                 action_links: [
                   { text: 'Code', href: 'http://github.com/facebook/connect-js' }
                 ],
                 user_message_prompt: 'Share your thoughts about Connect'
               },
               function(response) {
                 if (response && response.post_id) {
                   alert('Post was published.');
                 } else {
                   alert('Post was not published.');
                 }
               }
             );
            return true;*/
        },

        fbLoginRequestPermissions : function() {
            FB.init({appId: "295594696058", status: true, cookie: true, xfbml: true});
            FB.login(function(response) {
            if (response.session) {
                    // user logged in, do whatever here\
                } else {
                    // user cancelled login
                }
            },{perms:"offline_access,user_events,email,user_hometown,user_birthday"});

            return false;
        }

}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
                this.fullName = BrowserDetect.browser + ' ' + BrowserDetect.version + ' / ' + BrowserDetect.OS;
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

BrowserDetect.init();

function getWindowHeight() {
        var windowHeight = 0;
        if (typeof(window.innerHeight) == 'number') {
                windowHeight = window.innerHeight;
        }
        else {
                if (document.documentElement && document.documentElement.clientHeight) {
                        windowHeight = document.documentElement.clientHeight;
                }
                else {
                        if (document.body && document.body.clientHeight) {
                                windowHeight = document.body.clientHeight;
                        }
                }
        }
        return windowHeight;
}
function setContent(elId) {
        if (document.getElementById) {
                var windowHeight = getWindowHeight();
                if (windowHeight > 0) {
                        var contentElement = document.getElementById(elId);
                        var contentHeight = contentElement.offsetHeight;
                        if (windowHeight - contentHeight > 0) {
                                //contentElement.style.position = 'relative';
                                contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px';
                        }
                        else {
                                //contentElement.style.position = 'static';
                        }
                }
        }
}


$(document).ready(function() {

	Vykupto.init();

});


