var isOldIE = jQuery.browser.msie && jQuery.browser.version.substr(0,1) < 7;

function adjustScrolling() {
	myWidth = document.documentElement.clientWidth;
	
	difference = (1024 - myWidth) / 2;
	if (jQuery.browser.safari) {
		topPosition = window.pageYOffset;
	} else {
		topPosition = $('html')[0].scrollTop;
	}
	
	window.scrollTo(difference, topPosition);
}



if (!jQuery.browser.safari) { adjustScrolling(); } else { setTimeout('adjustScrolling()', 10); }

$(document).ready(function() {
	
	try {
		if (!isOldIE) {
			$('#pageContent img[alt][width][height]').each(function(iKey, eImg) {
				var eImg = $(eImg);
				if (!eImg.hasClass('nowrapper')) {
					var sImageAlign = eImg.attr('align');
					if (sImageAlign == '') sImageAlign = 'left';
					
					if (sImageAlign == 'left' || sImageAlign == 'right') {
						iImageWrapperWidth = parseInt(eImg.width()) + parseInt(eImg.css('padding-left')) + parseInt(eImg.css('padding-right')) + parseInt(eImg.css('border-left-width')) + parseInt(eImg.css('border-right-width'));
		
						var eImageWrapper = $(document.createElement('span'));
						eImageWrapper.addClass('imageWrapper');
						eImg.wrap(eImageWrapper);
						eImageWrapper = eImg.parent();
						eImageWrapper.append('<em>' + eImg.attr('alt') + '</em>');
						eImageWrapper.css('width', iImageWrapperWidth + 'px');
						eImg.attr('align', '');
						eImg.css('margin', 0);
						eImageWrapper.css('float', sImageAlign);
				
					}
				}
			});
		}
	} catch(err){}
	
	try {
		$('a[href^="http://"],a[href^="http://"],a[href$=".pdf"]').click(function(oEvent){
			window.open(this.href);
			return false;
		});
	} catch(err){}
	
	$('body#index_index div#lsite li.tandem').mouseover(function(){
		$('div#tandem h2').addClass('hover');
	});
	$('body#index_index div#lsite li.tandem').mouseout(function(){
		$('div#tandem h2').removeClass('hover');
	});
	$('body#index_index div#lsite li.sauteurs-reguliers').mouseover(function(){
		$('div#regulier h2').addClass('hover');
	});
	$('body#index_index div#lsite li.sauteurs-reguliers').mouseout(function(){
		$('div#regulier h2').removeClass('hover');
	});
	
	$(window).resize(function(){
		adjustScrolling();
	});
	
	$('#voltige_achat-certificat-cadeau form#addCertificate').submit(function(e){
		if ($('input[name="os1"]').val() == '' || $('input[name="os2"]').val() == '' || $('select[name="os0"]').val() == '') {
			e.preventDefault();
			alert("Tous les champs sont obligatoire.\n\nVérifier le formulaire et reassayer.");
		} else {
			setTimeout('$(\'input[name="os1"], input[name="os2"], select[name="os0"]\').val("");', 2000);
			setTimeout("$(\"#pageContent .CL2 h2 span\").text(\"Ajout d'un autre certificat\")", 2000);
		}
	});
});

CMApplication = {
    Bootstrap: {
        /**
         * Start the bootstrapper by executing each _init method of the
         * bootstrapper.
         */
        run: function() {
            for (var p in this) {
                if (p.indexOf('_init') === -1) continue;

                this[p]();
            }

        }
    },

    Viewport: {
        width: null,
        height: null,
        adjust: function() {
            // the more standards compliant browsers
            // (mozilla/netscape/opera/IE7) use window.innerWidth and
            // window.innerHeight

            if (typeof window.innerWidth != 'undefined')
            {
                 this.width = window.innerWidth,
                 this.height = window.innerHeight
            }

           // IE6 in standards compliant mode (i.e. with a valid doctype as the
            // first line in the document)

            else if (typeof document.documentElement != 'undefined'
                && typeof document.documentElement.clientWidth !=
                'undefined' && document.documentElement.clientWidth != 0)
            {
                this.width = document.documentElement.clientWidth,
                this.height = document.documentElement.clientHeight
            }

            // older versions of IE

            else
            {
                this.width = document.getElementsByTagName('body')[0].clientWidth,
                this.height = document.getElementsByTagName('body')[0].clientHeight
            }

            this.height = this.height - 45;


            var isMSIE6 = false;
            if(navigator.userAgent.indexOf("MSIE 6") != -1) isMSIE6 = true;


            if (isMSIE6) {
                document.getElementById('container').style.height = this.height.toString() + 'px';
            } else {
                document.getElementById('container').style.minHeight = this.height.toString() + 'px';
            }
        }
    },
    
    Widgets: {
        Dialog: {
            className: null,
            dialogContainer: null,
            Types: {
                exception: 1,
                error: 2,
                notice: 3
            },
            Events: {
                close: function(event) {
                    event.preventDefault();

                    CMApplication.Widgets.Dialog.close();
                },
                submit: function(event) {
                    event.preventDefault();

                    var formSubmitted = $(this);

                    jQuery.ajax({
                        url: formSubmitted.attr('action'),
                        data: formSubmitted.serializeArray(),
                        type: formSubmitted.attr('method'),
                        dataType: 'json',
                        success: function(data, textStatus, XMLHttpResponse){
                            if (data.status == 'success') {
                                form = formSubmitted.trigger('successCallback', data);
                            } else {
                                form = formSubmitted.trigger('failCallback', data);
                                if($(form).attr('rel') == 'keep') {
                                    for(var i in data.messages) {
                                        for(var j in data.messages[i]){
                                            message = data.messages[i][j];
                                            if($('#'+i).parent('div.elements').children('.errors').length == 0){
                                                $('#'+i).parent('div.elements').append("<ul class='errors'><li>" + message + "</li></ul>");
                                            } else {
                                                $('#'+i).parent('div.elements').children('.errors').html('<li>'+message+'</li>');
                                            }
                                        }
                                    }
                                }
                            }
                            
                            if($(form).attr('rel') != 'keep') {
                                CMApplication.Widgets.Dialog.close();
                            }
                        }
                    });
                }
            },

            /**
             * Display a message in a dialog
             * 
             * @param message
             *            The message (text or html) that you want to display in the
             *            dialog
             * @param type
             *            The type of message
             * @see Dialog.Types
             * 
             * @exemple CMApplication.Widgets.Dialog.displayMessage("This is an
             *          exception", CMApplication.Widgets.Dialog.Types.exception);
             *          CMApplication.Widgets.Dialog.displayMessage("This is an error",
             *          CMApplication.Widgets.Dialog.Types.error);
             *          CMApplication.Widgets.Dialog.displayMessage("This is a notice",
             *          CMApplication.Widgets.Dialog.Types.notice);
             */
            displayMessage: function(message, type) {

                switch(type) {
                    case CMApplication.Widgets.Dialog.Types.exception:
                        title = "Erreur système";
                        className = 'systemError';
                        break;
                    case CMApplication.Widgets.Dialog.Types.error:
                        title = "Erreur";
                        className = 'error';
                        break;
                    case CMApplication.Widgets.Dialog.Types.notice:
                        title = "Attention";
                        className = 'notice';
                        break;
                }
                html = '<div id="DialogWidgetMessage" class="' + className + '"><h2><span>' + title + '</span></h2>' + message + '</div>';

                CMApplication.Widgets.Dialog.open(html, 400);
            },

            /**
             * Display the content of an url in a dialog
             * 
             * @param url
             *            The url to call (should be on same domain name)
             * @param width
             *            The optionnaly width of the the dialog
             * 
             * @exemple CMApplication.Widgets.Dialog.displayUrl("/fr/test.html");
             *          CMApplication.Widgets.Dialog.displayUrl("/fr/test.html", 200);
             *          CMApplication.Widgets.Dialog.displayUrl("/fr/test.html", '80%');
             */
            displayUrl: function(url, width) {
                var width;
                ajaxUrl = url;

                jQuery.ajax({
                    url: ajaxUrl,
                    type: 'get',
                    dataType: 'html',
                    async: false,
                    success: function(data, textStatus, XMLHttpResponse) {
                        CMApplication.Widgets.Dialog.displayContent(data, width);
                    }
                });
            },


            /**
             * Display some content into a dialog
             * 
             * @param content
             *            Can be text or html
             * @param width
             *            The optionnaly width of the the dialog
             * 
             * @exemple CMApplication.Widgets.Dialog.displayUrl("There is <strong>a test</strong>");
             *          CMApplication.Widgets.Dialog.displayUrl("There is <strong>a test</strong>",
             *          200); CMApplication.Widgets.Dialog.displayUrl("There is
             *          <strong>a test</strong>", '80%');
             */
            displayContent: function(content, width) {
                CMApplication.Widgets.Dialog.open(content, width);
            },

            /**
             * PRIVATE METHOD: Should not be used directly
             */
            open: function(content, width) {
                $('html').addClass('displayDialog');
                if (undefined === width) {
                    width = '700';
                }

                dContainer = CMApplication.Widgets.Dialog.dialogContainer;

                if (dContainer == null) {
                    CMApplication.Widgets.Dialog._init();
                }

                if (CMApplication.Widgets.Dialog.className !== null) {
                    $('#DialogWidget').addClass(CMApplication.Widgets.Dialog.className);
                } else {
                    $('#DialogWidget').attr('class', '');
                }
                $('#DialogWidgetContent').html(content);
                $('#DialogWidgetContainer, #DialogWidgetContent').css('width', width + 'px');
                
                if ($('body').scrollTop() > $('html').scrollTop()) {
                    scrolltopValue = $('body').scrollTop();
                } else {
                    scrolltopValue = $('html').scrollTop(); 
                }
                
                dContainer.css('top', scrolltopValue);

                heightDiff = CMApplication.Viewport.height - $('#DialogWidgetContainer').outerHeight();
                if (heightDiff < 0) {
                    /**
                     * For any reason, the 3 following lines was commented and this one
                     * was replacing them.
                     * 
                     * This single line do not allow to scrolldown if the content of the
                     * box is bigger then the box itself.
                     * 
                     * $('#DialogWidgetContainer').css('height',
                     * $('#DialogWidgetContainer').outerHeight() + 50);
                     */
                    newHeight = $('#DialogWidgetContainer').height() - Math.abs(heightDiff) - 20;
                    $('#DialogWidgetContainer').css('height', newHeight);
                    $('#DialogWidgetContent').css('height', newHeight - 30);
                    heightDiff = CMApplication.Viewport.height - $('#DialogWidgetContainer').outerHeight();
                }

                newPosition = 0;// heightDiff != 0 ? Math.ceil(heightDiff / 2) : 0;

                $('#DialogWidgetContainer').css('top', 25);
            },

            /**
             * Close the dialog
             * 
             * @exemple CMApplication.Widgets.Dialog.close();
             */
            close: function() {
                dContainer = CMApplication.Widgets.Dialog.dialogContainer;

                if (dContainer == null) return ;

                CMApplication.Widgets.Dialog.className = null;
                $('html').removeClass('displayDialog');
                $('#DialogWidget').attr('class', '');
                $('#DialogWidgetContent').html('');
                $('#DialogWidgetContainer').css('height', 'auto');
                $('#DialogWidgetContent').css('height', 'auto');
            },
            
            setClass: function(className) {
                CMApplication.Widgets.Dialog.className = className;
                if ($('#DialogWidget').length == 1) {
                    if (className === null) {
                        $('#DialogWidget').attr('class', '');
                    } else {
                        $('#DialogWidget').addClass(className);
                    }
                }
            },

            /**
             * PRIVATE METHOD: Should not be used directly
             */
            _init: function() {
                markup = '<div id="DialogWidget"><div id="DialogWidgetBackground"></div><div id="DialogWidgetContainer"><div id="DialogWidgetClose"><span>close</span></div><div id="DialogWidgetContent"></div></div></div>';
                CMApplication.Widgets.Dialog.dialogContainer = $(markup).appendTo('body');
                dContainer = CMApplication.Widgets.Dialog.dialogContainer;

                $('#DialogWidgetBackground,#DialogWidgetClose').live('click', CMApplication.Widgets.Dialog.Events.close);
                $('#DialogWidgetContent form:not(.noDynamicSubmit form):not(#DialogWidgetContent #premiumPrices form)').live('submit', CMApplication.Widgets.Dialog.Events.submit);
            }
        }
    }
}

jQuery.extend(CMApplication.Bootstrap, {
    _initViewportAdjustment: function() {
        CMApplication.Viewport.adjust();
        window.onresize = CMApplication.Viewport.adjust;
    },
    _initContest: function(){
        //CMApplication.Widgets.Dialog.displayUrl('/voltige/concours');

        $('#contestForm').live('successCallback', function(event, data) {
            $('#contestForm').removeAttr('rel');
        }); 
        $('#contestForm').live('failCallback', function(event, data) {
            messages = 0;
            if (data) {
	            for (var i in data.messages) {
	                messages++;
	            }
	        }
            if (messages == 0) {
                alert("Vous avez déjà participé aujourd'hui. Limite de 1 participation par jour par personne.");
                $('#contestForm').removeAttr('rel');
            }
        }); 
    }
});


$(document).ready(function(){
    CMApplication.Bootstrap.run();
});
