


var general =
{
	/**
	 * Initialize
	 */
	init: function()
	{
		layout.init();
		login.init();

		if($('.col form').length > 0) forms.init();
		// Local partners module
		if($('.local-partners').length > 0) partners.init();
		// Partner finder
		if($('.partnerfinder').length > 0) partners.partnerFinder();

        // Filter form
        if($('#filterform').length > 0) forms.initFilterForm();

		// Add 'no-border' class to li before the selected li
		$('.primary > li.selected').prev('li').addClass('no-border');
		// Add quote class to first p tag in blockquote
		$('blockquote p:first-child').addClass('quote');
		// Add class 'first' to first th & td in table
		$('table th:first-child').addClass('first');
		$('table td:first-child').addClass('first');

		// Initialize datapicker(s)
		if($(".datepicker").length > 0) $(".datepicker").datepicker({
			showOtherMonths: true,
			firstDay: 1,
			dateFormat: 'dd/mm/yy',
			showOn: "both",
            closeText: "X",
            nextText: '>',
		    buttonImage: "/backend/fratello/0.0.1/img/ico_calendar.png",
		    buttonImageOnly: true
        });
	}
}

var layout =
{
	/**
	 * Initialize
	 */
	init: function()
	{
		this.setRequiredFieldIndicators();
        this.parseExternalLinks();
	},

	/**
	 * Set required indicators adds * to elements which have a class="required"
	 */
	setRequiredFieldIndicators: function()
	{
		$('.required label').append('<span class="indicator">*</span>');
	},

    parseExternalLinks: function()
    {
        $('a[rel=external]').click(function(e){
            open(this.href);
            e.preventDefault();
        });
    }
};

var login =
{
	init: function()
	{
		// Move some HTML stuff around
		login.positionLogin();

		$('.secundary .login a').click(function(e) {
			login.toggleLogin(true);

			e.preventDefault();
		});

		// Login form
		$('#btn-login').click(function(e) {

            e.preventDefault();

            // ajax call to login
            $.post('/en/login', {'email': $('#email').val(), 'password': $('#login #password').val(), 'remember': $('#remember').val()}, function(data){
                
                // successful login?
                if(data == 1)
                {
                    // reload page
                    window.location = window.location;
                }
                else
                {
                    login.toggleError(true);
                    login.toggleLogin("error");
                }
            });

			return false;
		});

		// Listen for changes
		login.attachLoginListeners();

	},

	positionLogin: function()
	{
		// Get the login form from HTML and place it in the HTML of the #header
		$('#header .container').append($('#login'));

		$('#login').append('<a href="#" title="Close" id="btn-close">Close</a>');
		
		$('#btn-close').live("click", function(e) {
			login.toggleLogin(false);

			e.preventDefault();
		});

		// Get the secundary nav from HTML and place it in #header
		$('#header .container').append($('#nav .secundary').show());

        // hide error messages
        $('#login dd.error').hide();
	},

	toggleError: function(state)
	{
		if(state) 
		{
			$('#login').addClass('error');
			$('.secundary .login').addClass('error');

            // show error messages
            $('#login dd.error').show();
		}
		else {
			$('#login').removeClass('error');
			$('.secundary .login').removeClass('error');
			$('#login dd.error').hide();
		}
	},

	toggleLogin: function(state)
	{
		var height;
		var callback = null;

		switch(state)
		{
			case true:
				height = "185px";
				break;

			case false:
				height = "120px";
				// When login is closed again, reset error
				callback = function() { login.toggleError(false); }
				break;

			case "error":
				height = "215px";
				break;
		}

		$('#login').show();

		// Animate login area
		$('#header .container').animate({
			height: height

		}, 500, 'swing', callback);
	},

	attachLoginListeners: function() {
		// username field
		$email = $('#email');
		$label = $('#email-value');

		// Attach event to main searchbox
		login.attachEvents($email, $label, 'text');

		// Attach event to password field
		login.attachPasswordEvents();

	},

	attachEvents: function($input, $label, type) {
		if ($input.length > 0 && $label.val() != null) {
			// Extract the label
			var initialValue = $label.val();

			// Create temp array to store the initial value of the searchbox
			var object = new Array();
			object['initialValue'] = initialValue;

			// Function to call the process action
			var func = function(e){
				login.handleEvent(e, object, type)
			};

			// Attach listener for initialValue change
			$input.focus(func);
			$input.blur(func);
			$input.keydown(func);
		}

		$input.trigger('blur');
	},

	handleEvent: function(e, obj, inputType){
		// Which type of event is fired?
		switch (e.type) {
			case 'focus':
				// Hide the initialValue
				if (e.target.value == obj.initialValue) {
					e.target.value = '';
					$(e.target).removeClass('inactive');
				}
				break;

			case 'blur':
				// Show the initialValue
				if (e.target.value == '') {
					e.target.value = obj.initialValue;
					$(e.target).addClass('inactive');
				}
				break;
        }
	},

	attachPasswordEvents: function() {
		$password = $('#password');
		$label = $('#password-label');

		// Create temp array to store the initial value of the searchbox
		var passwordObject = new Array();
		passwordObject['id'] = 'password';

		// Function to call the process action
		var passwordFunc = function(e){
			login.handlePasswordEvent(e, passwordObject)
		};

		// Attach listener for initialValue change
		$password.focus(passwordFunc);
		$password.blur(passwordFunc);
		$password.keydown(passwordFunc);

		// Create temp array to store the initial value of the searchbox
		// Create temp array to store the initial value of the searchbox
		var labelObject = new Array();
		labelObject['id'] = 'label';

		// Function to call the process action
		var labelFunc = function(e){
			login.handlePasswordEvent(e, labelObject)
		};

		// Attach listener for initialValue change
		$label.focus(labelFunc);
		$label.blur(labelFunc);
		$label.keydown(labelFunc);

		//$password.trigger('blur');
	},

	handlePasswordEvent: function(e, obj){
		// Which type of event is fired?
		$password = $('#password');
		$label = $('#password-label');

		if(obj.id == 'label')
		{
			switch (e.type) {
				case 'focus':
					// Hide the initialValue
					$label.hide();
					$password.show().focus();
					break;

				case 'blur':
					// Show the initialValue
					if (e.target.value == '') {
						$password.hide();
						$label.show();
					}
					break;
			}
		}
		else
		{
			switch (e.type) {
				case 'focus':
					break;

				case 'blur':
					// Show the initialValue
					if (e.target.value == '') {
						$label.show();
					}
					break;
			}
		}

	}
};

var forms = {
	init: function() {
		$('dd .field').focus(function(e) {
			// Assign focus class to dd parent
			$(this).parent().addClass('focus');
			// Assign focus class to dt
			$(this).parent().prev('dt').addClass('focus');
		});

		$('dd .field').blur(function(e) {
			// Remove focus class form dd parent
			$(this).parent().removeClass('focus');
			// Remove focus class from dt
			$(this).parent().prev('dt').removeClass('focus');
		});

		$('#partner').click(function() {
			$target = $('#partner-select');

			if ($(this).attr('checked')) $target.show();
			else $target.hide();
		});

        $('#country_id').change(function() {
            if($(this).val() == 'US') $('#select-region').show();
            else $('#select-region').hide()
        });

        $('#country_id').change();
	},

    initFilterForm: function() {
        $('select').change(function() {
            $(this).parent('form').submit();
        });
    }
};

var partners = {
	init: function() {
		$('#country').change(function() {
			if($(this).val() != 0)
			{
				$.getJSON('/ajax/partners', {countryId: $(this).val()}, function(data) {
					$('#partners').html(data['html']);
				});
			}
			else
			{
				$('#partners').html('');
			}
		});

		// If country id is given in url
		if($.getUrlVar('country'))
		{
			var countryId = $.getUrlVar('country');

			// Check if countryId == number
			if((parseFloat(countryId) == parseInt(countryId)) && !isNaN(parseInt(countryId)))
			{
				$.getJSON('/ajax/partners', {countryId: countryId}, function(data) {
					$('#partners').html(data['html']);
				});

				$('#country').val(countryId);
			}

		}
	},

	partnerFinder: function() {
		$('#country').change(function() {
			$(this).parent('form').submit();
		});
	}
};

$(document).ready(function()
{
	// General javascript interaction
	general.init();

});

// jquery extension to extract url params

$.extend({
	getUrlVars: function(){
		var vars = [], hash;
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

		for(var i = 0; i < hashes.length; i++)
		{
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
		return vars;
	},

	getUrlVar: function(name){
		return $.getUrlVars()[name];
	}
});