/**
 * Zahia website
 *
 * @author Davy De Pauw <davy@marlon.be>
 * @copyright Marlon bvba <http://www.marlon.be>
 *
 */

/**
 * Layout related javascript code.
 */
var layout = {
    /*
     * Initialize the layout.
     */
    init : function()
    {
		// Replace the fonts (if needed)
		if ($('.cr').length > 0)
		{
	   		layout.replaceFonts();
		}

		// Initialize Cufon
		Cufon.now();

		// Add quote images where needed
		if ($('.quote').length > 0)
		{
            layout.addQuotes();
		}

        layout.parseLinks();
        layout.parseImages();

        // Init spotlight
        if($('.spotlight').length > 0) layout.spotlight.init();

        // Center image
        if($('.center-image').length > 0) {
            var $img = $('.center-image img');
            
            $img.css({
                'margin-top': -($img.height() / 2) + 'px',
                'top': '50%'
            });
        }

        $('#sidebar').wrap('<div class="fix"></div>');

        if($('.col-main .faq').length > 0) layout.parseFaq.init();
    },

    /**
     * Replace fonts marked for Cufón replacement
     */
    replaceFonts : function()
    {
		// Replace font using Cufon
		Cufon.replace('.cr');

		// Show the replaced text
		$('.cr').css('visibility', 'visible');
    },

    setMinHeight: function($main, $side)
    {
	    // Get current widths
	    var mainHeight = $main.outerHeight();
	    var sidebarHeight = $side.outerHeight();
	    var padding = $main.outerHeight() - $main.height();
        var sidebarPadding = $side.outerHeight() - $side.height();

        if(mainHeight > sidebarHeight)
        {
            if(!$main.parent().hasClass('ext-footer'))
            {
                $side.height(mainHeight - padding - sidebarPadding);
            }
            else
            {
                $side.height(mainHeight - padding);
            }
        }
        else if(mainHeight < sidebarHeight)
        {
            $main.height(sidebarHeight - padding);
        }
    },


    /*
     * Add span elements to elements with class 'quote' on them.
     */
    addQuotes : function()
    {
        // Add quote span
        $('.quote').prepend('<span class="quote-sign"></span>');
    },

    parseLinks: function()
    {
        $('a.more').each(function(i) {
            $parent = $(this).parent();

            $parent.click(function(e) {
                window.location = $(this).find('a.more').attr('href');
            });

            $parent.addClass('clickable');
        });
    },

    parseImages: function()
    {
        // Add landscape or portrait classes to parent
        $('img.thumb').each(function(i) {
            $(this).load(function() {
                $parent = $(this).parent();

                if($(this).width() > $(this).height())
                {
                    $parent.addClass('landscape');
                }
                else if($(this).width() < $(this).height())
                {
                    $(this).parent().addClass('portrait');
                }
                
                // Determine the type
                if($parent.is('li') && $parent.parent().hasClass('row'))
                {
                    $parent.css('padding-top', $(this).height() + 25);
                }
                else if($parent.is('div'))
                {
                    $parent.css('min-height', $(this).height() + 20);
                }
                
            });

            // Trigger load when image is already cached
            var src = this.src;
            this.src = "";
            this.src = src;
        });

        // Add landscape or portrait classes to img tag
        $('img.image, .blog .col-main .article img').each(function(i) {
            $(this).load(function() {
                if($(this).width() > $(this).height())
                {
                    $(this).addClass('img-landscape');
                }
                else if($(this).width() < $(this).height())
                {
                    $(this).addClass('img-portrait');
                }
            });

            // Trigger load when image is already cached
            var src = this.src;
            this.src = "";
            this.src = src;
        });
    },

    parseFaq: {
        init: function()
        {
            $('.questions a').each(function(i) {
                $(this).click(function(e) {
                    // Reset selected classes
                    layout.parseFaq.reset();

                    // Assign class to faq answer
                    var $dt = $($(this).attr('href'));
                    $dt.addClass('selected');
                    // dd
                    $dt.next().addClass('selected');

                    layout.setMinHeight($('#pagecontent'), $('#sidebar-container'));
                })
            });

            $('.answers a.top').click(function(e) {
                layout.parseFaq.reset();
            });
        },

        reset: function()
        {
            $('.answers dt, .answers dd').removeClass('selected');
            layout.setMinHeight($('#pagecontent'), $('#sidebar-container'));
        }
    },

    spotlight: {
        i: 0,
        timeOut: null,

        init: function()
        {
            $('.controls a').click(function(e) {

                e.preventDefault();

                // Get container
                var c = layout.spotlight;

                // Li parent()
                $li = $(this).parent();

                // Current index
                var currIndex = $li.index();

                // Set index to currentItem
                c.i = currIndex;

                // Get target to be scrolled to
                var $target = $($(this).attr('href'));

                // Reset selected states
                $('.controls li').attr('class', '');

                // Set selected state for current item
                $(this).parent().attr('class', 'selected');

//                $('.spotlight-wrapper').scrollTo($target, {axis:'x'});
                $('.spotlight-wrapper').scrollTo($target, 500);

                // Clear timeout
                clearTimeout(c.timeOut);

                // Calculate next item
                if(currIndex < $li.siblings().length)
                {
                    c.i++;
                }
                else
                {
                    c.i = 0;
                }

                // Call next spotlight in 5 seconds
                c.timeOut = setTimeout("layout.spotlight.animate()", 6000);
            });

            // Select first item
            $('.controls a:first').trigger('click');
        },

        animate: function()
        {
            $('.controls li:eq(' + (layout.spotlight.i) + ') a').trigger('click');
        }
    }
}

/**
 * Ads related scripts.
 */
var ads =
{
    /*
     * Initialize the ads.
     */
    init : function()
    {
        // Create property settings for the ad banner swf
        var adBannerVariables =
        {
            xml: '/bannerssource.aspx',
            delay: '4',
            mdelay: '4',
            ar: 'true'
        };
        var adBannerParams = {};
        var adBannerAttributes = {};

        // Embed the swf
        swfobject.embedSWF('/swf/BannerSystem.swf', 'ad-swf', '310', '80', '9.0.0', false, adBannerVariables, adBannerParams, adBannerAttributes);
    }
}

/**
 * Form related javascript code.
 */
var forms = {
    /*
     * Initialize the forms (if any)
     */
    init : function()
    {
		// Check if any fieldsets are present (fieldset 'divide' forms)
		if ($('fieldset').length > 0)
		{
		    // Set button hover
			forms.setButtonHover();
	
		    // Set focus listeners
			forms.setFocusListeners();
			
			// Set mandatory fields
			forms.setRequiredFields();

            forms.initCheckboxes();
		}
    },
	
	/*
	 * Set button hover.
	 */
	setButtonHover : function()
	{
		// Button hover
	    $('input.button').hover(
			function()
			{
			    // Add parent class to parent dd
		    	$(this).parent().addClass('hover');
			},
			function ()
			{
			    // Remove hover class from parent dd
		    	$(this).parent().removeClass('hover');
			}
	    );
	},
	
	/*
	 * Set focus/blur listeners.
	 */
	setFocusListeners : function()
	{
		// Field focus/blur
	    $('form .field').focus(function()
	    {
			// Add parent class to parent dd
			$(this).parent().addClass('focus');
	    });
	    $('form .field').blur(function()
	    {
			// Add parent class to parent dd
			$(this).parent().removeClass('focus');
	    });
	},
	
	/*
	 * Indicate required form fields
	 */
	setRequiredFields : function()
	{
		$('label.required').append('<span class="indicator">*</span>');

        // Indicate errors
		$('dd.error').append('<span class="error"></span>');

	},

    initCheckboxes: function()
    {
        $('input.checkbox').wrap('<span class="cb"></span>');
        
        /* see if anything is previously checked and reflect that in the view*/
        $("input.checkbox:checked").parent().addClass("checked");

        /* handle the user selections */
        $(".cb").click(function(e) {
            if($(this).hasClass('checked'))
            {
                $(this).removeClass("checked");
                $(this).find(":checkbox").removeAttr("checked");
            }
            else
            {
                $(this).addClass("checked");
                $(this).find(":checkbox").attr("checked","checked");
            }

            e.preventDefault();
        });
    }
}

$(document).ready(function()
{
   // Initialize the layout
   layout.init();

   // Init ads
   ads.init();

   // Initialize forms
   forms.init();
});


// Load event gets dispatched when all assets have been loaded
$(window).load(function()
{
    // Set main/sidebar height for both content block & extended footer
    layout.setMinHeight($('#pagecontent'), $('#sidebar-container'));
    layout.setMinHeight($('.ext-main'), $('.ext-side'));
});