/* -*- mode: javascript; -*-  */
var margin = 8;
var preload =  1;

var jsReady = false;
var player_id = null;
var id_product;
var path_product;

/* don't overwrite console if there is one */
/*
if (typeof window.console == "undefined")
    window.console = {} 
console.log || (console.log = opera.postError)
*/

$.ifixpng('/themes/default/images/pixel.gif');

(function($) {
	$.fn.extend({
		ASCall: function(value) {
            return this.each(function() {
                this.sendToActionScript(value);
            });
		},
		debug_red: function() {
            return this.each(function() {
                $(this).css({ backgroundColor:"red"});
            });
		},
		mark_invoice: function() {
            return this.each(function() {
                var span = $(this).parent();
                $.getJSON('/json/invoice/'+$(this).attr('rel')+'/', function(data) {
                    if (data.result) {
                        span.html("prepared")
                    }
                });
            });
		},
		debug_size: function() {
            return this.filter(":visible").each(function() {
                if ($(this).is("div")) {
                    $(this).append('<div class="debug">'+$(this).width()+'x'+$(this).height()+'</div>');
                    /*$(this).css("border", "1px dotted blue");
                    $(this).css("width", $(this).width()-2);
                    $(this).css("height", $(this).height()-2);*/
                }
                if ($(this).is("img")) {
                    $(this).after('<div class="debug">'+$(this).width()+'x'+$(this).height()+'</div>');
                }
                if ($(this).is("form")) {
                    $(this).after('<div class="debug">'+$(this).width()+'x'+$(this).height()+'</div>');
                }
            });
		},
		active: function() {
            // active dynamic javascript elements, this fonction could be called 
            // at the #container level, #content or .block level
            // don't put calls outside the "if $(this).attr('id') == "
            
            return this.each(function() {
                
                if ($(this).attr('id') == 'container') {

                    $(this).find('#content').active();

                }

                $(".tooltip").jHelperTip({
                    trigger: "hover", 
                    source: "attribute", 
                    attrName: "rel",
                    opacity: 0.8, 
                    autoClose:true
                });

                // we get there twice: once, article div is there but empty,
                // then we get article description.
                if ($(this).attr('id') == 'article' && $(this).children().length) {
                    var zoomTT = $('.zoom_title').html();

                    // zoom plugin test
                    $('.images ul.browser').zoom({
                         divName: '#magnifier',
                         loupe: '/themes/colette/images/lens.png',
                         loupeInfo: {normal: zoomTT, zoomed: zoomTT},
                         stickyLoupe: true,
                         loaderImg: '/themes/colette/images/loader.gif',
                         drag: false,
                         cursor: 'url(/themes/colette/cursors/plus.cur), crosshair',
                         movingCursor: 'url(/themes/colette/cursors/minus.cur), move',
                         grabCursor: 'url(/themes/colette/cursors/openhand.cur), crosshair',
                         grabbingCursor: 'url(/themes/colette/cursors/closedhand.cur), move',
                         startEvent: 'click',
                         selectedCallback: function(event, $object){ $('.viewer p.legend').html($object.attr('title')); }
                    });
                }

                // #content initialisation
                if ($(this).attr('id') == 'content') {

                    $(this).find('.ffb-input').addClass('inlineblock');

                    $(this).find('.block').active();
                    
                    var api = $(this).find(".item_scroller").scrollable({
                               size: 10, vertical: false, speed: 600, activeClass: 'selected',
                               next:'.next', prev:'.prev', items: '.browser',
                               onSeek: function()  { 
                                   this.root.find('.mpager').find('span').html( (this.getStatus().page+1) + '/' + this.getStatus().pages);
                               }     
                               }); 

                    var position = $(this).find(".mpager").attr('id');
                    if (position) {
                        $(this).find('.item_scroller').scrollable("seekTo", (position < 2 ? 0 : position - 2) );
                    }

                    $(this).find('.camelize').camelize();
                    
                    $(this).collapse();
                    
                    $(this).find('.expandable').children('.right').prepend('<div class="expand expand_button">+</div>');
                    
                    $(this).find('.fixpng').ifixpng();

                    $(this).find(".shadow_block").poetize();
                    
                    $(this).find('.blogs ul.blog').blogroll();
                    
                    //setTimeout("$('.blog ul.blog img.overlay').fadeOut()", 3000);

//                     $(this).find("#zoom_no").magnify({
//                            showEvent: 'click',
//                            hideEvent: 'click',
//                            lensWidth: 328,
//                            lensHeight: 328,
//                            preload: false,
//                            stagePlacement: 'right',
//                            lensCss: { backgroundColor: '#0067B1', border: '0px', opacity: 0.3 },
//                            stageCss: { 'margin-top': '15px', border: '1px solid #ccc' }
//                     });

//         $(this).find('#test2').mousewheel(function(event, delta) {
// 						if (delta > 0)
// 							$(this).find('#logger').append('#test2: up ('+delta+')<br />');
// 						else if (delta < 0)
// 							$(this).find('#logger').append('#test2: down ('+delta+')<br />');
// 						return false; // prevent default
// 					});
				
                    $('.waterbar').hover(function(){$(this).find('dl').fadeIn(500);},function(){$(this).find('dl').fadeOut(100);})
                }

                if ($(this).hasClass("block")) {

                    $(this).find(".nojs").hide();
                    $(this).find(".onlyjs").show();

                    // transform a-z list into columns
                    $('ul.a_z').columnize({width:282, doneFunc: function() { 
                        $('ul.a_z div li.letter').each(function() { $(this).css('margin-top', '4px'); });
                        $('ul.a_z div li:first-child').not('li.letter').each(function() { 
                            $(this).css('margin-top', '22px'); 
                        });
                        $('ul.a_z li a').each(function(i){
                            var newHref = $(this).attr('rev').replace(/,/g,"/"); 
                            $(this).attr('rev', newHref).attr('href', newHref); 
                        }); 
                    }});

                    $(this).find(".thumb_scroller").scrollable({
                         size: 5, vertical: false, speed: 600, 
                         next:'.next', prev:'.prev', items: '.browser'
                    }); 
                    
                    $(this).find(".carousel").scrollable({
                         size: 2, vertical: true, speed: 300,
                         next:'.next', prev:'.prev', items:'.thumbnails',
                         onSeek: function()  { 
                             this.root.find('span').html( (this.getStatus().page * 2 + 1) + '/' + this.getStatus().pages * 2);
                         }     
                    }); 
                   
                    $(this).find(".bybrand select").uniform();
                    $(this).find(".options select").uniform();

                    $(this).find(".autoclick").autoClick();

                    $(this).find(".player").loadPlayer();

                    $(this).find(".modal").modal();

                    $.each($.browser, function(i) {
                        if ($.browser.mozilla){
                            /* inline-block equilvalent for mozilla */
                            $('.inlineblock').css('display','-moz-inline-box');
                        }
                        if ( ! $.browser.msie ){
                            $.jcorners(".embeddedfield",{radius:12});
                            $.jcorners(".rounded",{radius:12});
                            $.jcorners(".knob",{radius:15});
                        }
                    });

//                     $(this).find(".go_account").jHelperTip({
//                             trigger: "click", autoClose: "false", opacity: 0.9, dC:"#wishlist_help"
//                     }); 

//                     $(this).find("#wishlist_redirect").jHelperTip({
//                             trigger: "click", dC:"#redirect_help", 
//                             topOff: -60, leftOff: -100, opacity: 0.9
//                     }); 

//                     $(this).find(".tooltip").tooltip({
//                             delay: 0 , track: true
//                     });

					$(this).find('ul.browser li a').click(function(evt) {
					  if (!(Colette.isStdClick(evt))) { return true; }
					  
						tarImg = '';
						evt.preventDefault();
						img = $(this).attr('href');
						var reg = new RegExp('[0-9]','gi');
						if(img.match(reg)) tarImg = ''+img.match(reg);
						var id = tarImg.split(',');
						tarImg = '';
						for(key in id) tarImg += id[key];
						
						tarImg = new RegExp(tarImg,'gi');
						
						var img = $('.gallery a img');
						img.parent().parent().find('a').attr('href', function() {
							var chaine = ''+this;
							if(chaine.match(tarImg)) {
								var target = $(this);
								target.html(img);
							}
						});
					});
                    
                    $(this).find(".gallery a").fancybox({
	                    'cyclic'		: true,
	                    'transitionIn'	: 'none',
	                    'transitionOut'	: 'none',
                        //'autoScale'     : true,
                        //'centerOnScroll' : true,
	                    'onComplete'	:	function() {
							//if ($.browser.webkit) {
								var winHeight = document.documentElement.clientHeight;
								var imgHeight = $(this).attr('height');
                                //alert(imgHeight);
								var marge = (winHeight - imgHeight)/2.5;
                                $('#fancybox-wrap').css({
                                    position:   'fixed',
                                    top:        marge
                                });
                            //}
	                    }
                    });
                    
                    /* Call contact form using fancybox */
                    $(this).find('.contact_form_trigger').fancybox({
                        margin : 0,
                        padding : 0,
                        showCloseButton : false,
                        href: "/block/contact-us/",
                        onStart : function()
                        {
                            /* Extract the id from the url */
                            path_product = SWFAddress.getValue();
                            id_product = path_product.match('article/[0-9]+/').toString();
                            id_product = id_product.match('[0-9]+').toString();
                        },
                        onComplete    :   function() {
                            $("#fancybox-inner").addClass('loaded');
                            $("#key_form").active();
                            $("#contact_form").active();
                        }
                    });
                }
            });
		},
        submit: function() {
            return this.each(function() {
                this.submit();
            });
        },
        camelize: function() {
            return this.each(function() {
                $(this).html( $(this).html().replace(/ \b/g, '') );
            });
        },
        autoClick: function() {
            return this.each(function() {
                this.active_left_cover = window.setTimeout("$('.autoclick').click();", 5000);
            });
        },
        blogroll: function() {
            return this.each(function() {

                if ($(this).is("ul")) {

                    $(this).children("li").blogroll();

                	var  preload  = new  Array();
	                for(var i = 1; i <= 10; i++){
    		            preload[i]= new Image();
		                $(preload[i]).load(function(){}).attr("src", "/themes/blog/images/circles/r"+i+".gif");
	                }
                }

                if ($(this).is("li")) {
                
                   $(this).find("a.portrait").hover( function() {
                        $(this).find("img.overlay:first").fadeOut();
                    }, function() {
                        $(this).find("img.overlay:first").fadeIn();
                    });
                }

            });
        },
        loadPlayer: function() {
            return this.each(function() {

                var placeholder = $(this).children(".placeholder");
                var params = $(this).children(".player_params");
                var media_id = placeholder.attr('id').substr(7);
                if (!media_id) {
                    placeholder.attr('id','player_0');
                    media_id = 'player_0';
                }

                var sendfriend_id = placeholder.attr('rel');

                var flash_vars = { id: media_id,
                                    path: "http://www.colette.fr/" + placeholder.html(),
                                    base_path: '/',
                                    sendfriend_id: sendfriend_id
                };

                params.children("li").each(function() {
                    var name = $(this).attr("class");
                    flash_vars[name] = $(this).html();
                });

                swfobject.embedSWF("/player.swf", placeholder.attr('id'), "100%", "100%", "8", "/themes/default/flash/playerProductInstall.swf", flash_vars , {allowFullscreen: true}, { id: placeholder.attr('id') });  //wmode: 'opaque', 

            });
        },
		poetize: function() {
            return this.filter(".shadow_block").each(function() {
                
                $(this).load('/block/poetry/', {}, function(){

                    var ul = $(this).children('ul');
                    var diff = $(this).height() - $(ul).height();
                    var i = 0;
//                     while (diff > 0 && i < 10) {
//                         var ft = $(this).css('font-size').replace(/px/, '');
//                         $(this).css('font-size', (parseInt(ft) + 1) + 'px');
//                         diff = $(this).height() - $(ul).height();
//                         i=i+1;
//                     }
//                     i = 0;
//                     while (diff < 0 && i < 10) {
//                         var ft = $(this).css('font-size').replace(/px/, '');
//                         $(this).css('font-size', (parseInt(ft) - 1) + 'px');
//                         diff = $(this).height() - $(ul).height();
//                         i=i+1;
//                     }
                });

            });
		},
        complete: function(viewport_height) {
            return this.each(function() {

                /* viewport level call */

                if ($(this).hasClass("viewport")) {
                    $(this).children(".column").complete( $(this).height());
                }

                /* column level call */

                if ($(this).hasClass("column") && viewport_height) {

                    // get selected column height
                    var column_height = 0;
                    $(this).children(".block:visible").each(function() {
                        column_height = column_height + margin + $(this).height();
                    });

                    var shadow = $(this).children(".shadow_block");

                    // If height is less than viewport_height we add a shadow block to fill in empty space
                    if (column_height + 10 < viewport_height) {

                        if (! shadow.is("div")) {

                            // empty the div to prevent some refresh 
                            shadow = $(this).children(".block:first").clone().empty();
                            shadow.removeClass('collapsable block');
                            shadow.addClass('shadow_block');
                            $(this).append(shadow);
                            shadow.poetize();


                        }

                        shadow.height(viewport_height - column_height - margin);
                        shadow.fadeIn();

                    }
                    // if column height is more than vp height, we remove any possible shadow
                    if (column_height >= viewport_height) {
                        if (shadow.is("div")) {
                            shadow.fadeOut();
                        }
                    }
                }
            });
		},
		expand: function() {
            return this.each(function() {

                if ($(this).hasClass("expand")) {
                    
                    var collapsed = $(this).parents(".block");

                    // main container (contains both expanded and non-expanded version)
                    var column = collapsed.parents(".column");

                    // The first time this method is called we need to:
                    // 1. get content from server
                    // 2. add colapse button
                    //
                    if (! collapsed.hasClass("ready")) {

                        var expanded = collapsed.clone();
                        expanded.addClass('expanded '+expanded.attr('expanded_class'));

                        expanded.load('/block'+expanded.attr('expanded')+'/', function(){

                            $(this).append('<div class="collapse collapse_button">-</div>');
                            collapsed.before(expanded);
                            collapsed.addClass('ready');

                            column.children(".shadow_block").hide();
                            collapsed.hide();

                            expanded.active();

                            expanded.show();

                        });

                    } else { // already got content

                        column.children(".shadow_block").hide();
                        
                        collapsed.fadeOut("normal", function() {
                            var expanded = $(this).prev();
                            expanded.fadeIn("normal", function() {
                                var viewport = $(this).parents(".viewport");
                                viewport.complete();
                            });
                        });

                    }

                }

            });
		},
		collapse: function() {
            return this.each(function(callback) {

                /* #content level call */

                if ($(this).attr("id") == 'content') {

                    $("div.collapsable").collapse();
                    $(this).show();

                }

                /* block level call */

                if ($(this).hasClass("block") && $(this).hasClass("collapsable")) {

                    var expanded = $(this);
                    var button = expanded.children("collapse_button");

                    // called at .block level

                    if (button.is("div")) {
                        return $(button).collapse;
                    }
                    
                    // no button, first call, expand/collapse
                    // switch creation 
                    expanded.hide();
                    expanded.append('<div class="collapse collapse_button">-</div>');

                    var column = expanded.parent(".column");
                    var viewport = expanded.parent(".viewport");
                    var collapsed = expanded.clone();

                    collapsed.removeClass("collapsable");
                    collapsed.addClass('collapsed ready '+expanded.attr('collapsed_class'));

                    collapsed.load('/block'+expanded.attr('collapsed')+'/', function(){

                        if (!collapsed.hasClass("noexpand")) {
                            $(this).append('<div class="expand expand_button">+</div>');
                        }
                        expanded.after(collapsed);
                        collapsed.show();
                    });
                 
                }

                if ($(this).hasClass("collapse")) {

                    var expanded = $(this).parents(".block");
                    expanded.hide();

                    var collapsed = expanded.next();
                    var viewport = expanded.parent(".column").parent(".viewport");
                    // Hide any child
                    viewport.children(".column").children(".shadow_block").hide();
                    collapsed.show();
                    viewport.complete();

                }

            });
		},
		run: function() {
            return this.filter(".xxx").each(function() {


            });
		}
	});
})(jQuery);



Colette = new function() {

    this.active_left_cover = null;

    this.toString = function() {
        return '[class Colette]';
    }

    this.isReady = function(id) {
        return jsReady;
    }

    // This function is only called for the first swf url
    // initialisation  inside #content shoudl go in $.active()

    this.bodyFinalize = function(path) {

        // top music player is not inside #content

        var placeholder = $('#playlist').children(".placeholder");
        var track_id = placeholder.attr('id').substr(9);
        var autoplay = placeholder.hasClass('silent') ? 0 : 1;

        player_id = placeholder.attr('id');

        swfobject.embedSWF("/playlist.swf", placeholder.attr('id'), "100%", "100%", "9", "/themes/default/flash/playerProductInstall.swf", {
               base_path: '/',
               xml_url: '/api/playlist/',
               link1_label: 'ESHOP',
               link2_label: 'LIVE',
               trigger_url: '/json/playlist/',
               autoPlay: autoplay
        }, {}, { id: placeholder.attr('id') });

        // only live call can be set outside of $.active() recursive loop

        $('.autoclick').live('click', function() { 
            if (this.active_left_cover) {
                window.clearTimeout(this.active_left_cover);
            }
        });

        $('a[rel*=external]').live('click', function() {
            window.open(this.href, 'blog');
            return false;
        });

        $('.expand').live('click', function() { $(this).expand(); });
        $('.collapse').live('click', function() { $(this).collapse(); });
        $('.popup').live('click', function () { Colette.popup($(this)); return false; });
        $('#brand_selection').live('change', function() { SWFAddress.setValue($('#brand_selection').val()); })

        $('.mark_invoice').live('click', function() { $(this).mark_invoice(); });

        // XXX swfobject bug ?
        setTimeout("", 1250);

    }

    this.play = function(id) {
        $('#'+player_id).ASCall('/api/playlist/'+id+'/');
    }

    this.playarticle = function(id) {
        $('#'+player_id).ASCall('/api/playlist/article/'+id+'/');
    }
    
    this.playmedia = function(id) {
        $('#'+player_id).ASCall('/api/playlist/media/'+id+'/');
    }

    this.sendToJavaScript = function(id) {
        $('#top_status').html(value);
    }

    this.partialChange = function(element) {
        element.blur();
        $(element).css('cursor', 'wait');
        SWFAddress.setValue($(element).attr('href'));
        $(element).css('cursor', 'default');
    }

    this.handleClick = function(element, event) {
        element.blur();
        $(element).css('cursor', 'wait');
        SWFAddress.setValue(element.rev);
        $(element).css('cursor', 'default');
    }

    this.handleActionClick = function(element, event) {
        element.blur();
        $(element).css('cursor', 'wait');
        Colette.loadPath(SWFAddress.getPath()+element.rev);
        $(element).css('cursor', 'default');
    }

    this.submitOptions = function(button, path) {

        var form = $(button).parents('form');
        var params = $(form).serialize();
        if (SWFAddress.getValue().indexOf('?') > 1) {
            Colette.loadPath(SWFAddress.getValue()+'&'+params);
        } else {
            Colette.loadPath(SWFAddress.getValue()+'?'+params);
        }
    }

    this.handleChange = function(event) {
        $('.favicon').attr('href','/themes/colette/images/favicon.ico');
        if (preload == 1) {
            $('#container').active();
            preload = 0;
        } else {
            Colette.loadPath(event.value);
        }
    }

    this.isStdClick = function(evt) {
      return evt.ctrlKey || evt.metaKey ? false : true;
    }

    this.loadPath = function(path) {

        // default namespace/target
        var namespace = '/section';
        var target= '#content';

        // article top menu already loaded
        if (path.match(/^\/eshop\/article\//) && ($('#article').length && ($('#article').get(0).nodeName.toLowerCase() == 'div'))) {
            var r = /^(.*\/)(\d+)\/($|\?)(.*)/;
            var a = r.exec(path);
            var section_id = $('.top').attr('id') || 3;
            if (section_id && a && section_id == a[2]) {
                // same section, only reload block
                namespace ='/block/sc';
                target = '#article';
            }
        } else if (path.match(/^\/home\//) && $('#welike').length ) {
            var namespace = '/partial';
            var target = path.substr(9);
            target = '#' + target.substr(0,target.indexOf('/'));
            $('#content').show();
        } else if (path.match(/^section\/(.*)\/search\/article\//)){
            namespace = '';
        }

        // reencode query part (should be more generic)
        if (path.match(/\/search\//) && path.indexOf('?') > 1) {
            query = path.substr(path.indexOf('?') + 1);
            path = path.substr(0, path.indexOf('?')) + '?' + escape(query);
        }
        
        $("body").css('cursor', 'wait');

        $(target).load(namespace+path, function(data) {
            $(target).addClass('loaded').show();
            $(target).active();

            if (target == '#content' && ($('#article').length && ($('#article').get(0).nodeName.toLowerCase() == 'div'))) {

                var section_id = $(target).find('.top').attr('id') || 3;

                if (section_id && ! path.match(/^(.*\/)(\d+)\/($|\?)(.*)/)) {
                    if (path.indexOf('?') > 1) {
                        path = path.substr(0, path.indexOf('?'));
                        //console.log("path %s, query %s", path)
                    }
                    path = path + section_id + '/' ;
                    SWFAddress.setHistory(0);
                    SWFAddress.setValue(path);
                } else {
                    Colette.loadPath(path);
                }

                var selected_pos = $('.__scrollable >li.selected').prevAll().length;
                if (selected_pos > -1) {
                    $('#content .item_scroller').scrollable('seekTo', selected_pos+1);
                }
            }

            if (path.match(/(cart|wishlist|payment|signin|logout)/)) {
                Colette.reloadStatus();
            }

            if (target == '#article') {
                /* Replacing &amp; by & in title */
                var articleTitle = $('#article').find('h2').html();
                articleTitle = articleTitle.replace('&amp;','&');
                SWFAddress.setTitle(articleTitle + ' - ' + $('#article').find('h3').html() + ' - colette ');    
            } else if (target == '#content' && $('#title').html()){
                SWFAddress.setTitle($('#title').html()); 
            }

            SWFAddress.setHistory(1);

            $("body").css('cursor', 'default');
        });
    }
    
    this.submitContactForm = function(button, path) {
        var form = $(button).parents('form');
        
        var params = $(form).serialize() + '&' + $(button).filter(':submit').attr('name') + '=1' + '&id_product='+id_product+'&path_product='+path_product;
        var target = path || '/block/contact-us/';
        
        $('#content').css('cursor', 'wait');
        
        $.post(target, params, function(data)
        {
            $('#content').css('cursor', 'default');
            $('#fancybox-inner').html(data);
            $("#key_form").active();
            $("#contact_form").active();
        });
    }
    
    this.submitPrivateKey = function(button, path) {
        var form = $(button).parents('form');
        
        var params = $(form).serialize() + '&' + $(button).filter(':submit').attr('name') + '=1' + '&id_product='+id_product;
        var target = path || '/block/contact-us/';
        
        $('#content').css('cursor', 'wait');
        
        $.post(target, params, function(data)
        {
            $('#content').css('cursor', 'default');
            $('#fancybox-inner').html(data);
            $("#fancybox-inner").addClass('loaded');
            $("#key_form").active();
            $("#contact_form").active();
            
            if($(data).find('.feedback_key.success').length) {
                Colette.closeFancy();
                Colette.loadPath(path_product);
            }
        });
    }

    this.submitForm = function(button, path) {

        var form = $(button).parents('form');
        
        var params = $(form).serialize() + '&' + $(button).filter(':submit').attr('name') + '=1';
        var target = path || '/' + $('#path').html() || '/section' + SWFAddress.getValue();

        // Add waiting cursor
        $('#content').css('cursor', 'wait');

        $.post(target, params , function(data){

            $('#content').css('cursor', 'default');

            $("#content").html(data);
            $("#content").addClass('loaded');
            $("#content").active();

            if (target.match(/search/)) {
                // We already loaded result page, set SWFAddress but no real load...
                preload = 1;
                SWFAddress.setValue( target.replace(/\/section/,'') + '?' + params );
            }

            if (params.match(/(cart|login|signup)/)) {
                Colette.reloadStatus();
            }

        }, 'html');

    }


    this.reloadStatus = function() {
        $("#top_status").load('/block/status/', function(data){ });
    }

    this.changeWallpaper = function(block) {

        if ($(block).css('background-image').match("themes")) {
            $('body').css('background-color', '#FFFFFF');
            $('body').css('background-image', $(block).css('background-image'));
        } else {
            $('body').css('background-image', 'none');
            $('body').css('background-color', $(block).css('background-color'));
        }

    }

    /*this.popup = function(url, title) {*/
    this.popup = function($element) {
        window.open(SWFAddress.getPath()+$element.attr('rel'), $element.attr('title') ? $element.attr('title') : 'colette.fr', 'toolbar=1,location=1,status=1,menubar=1,scrollbars=1,resizable=1,width=960,left='+(screen.width-960)/2);
    }

    this.showImage = function(a) {
        var thumb = $(a).children();
        var selected = $(a).parents('.slideshow').find('.selected');
        var img = selected.find('img');
        var modal_img = selected.next().next().find('img');
		
        img.attr('src', thumb.attr('src'));
        img.attr('alt', thumb.attr('alt'));
        selected.find('span').html(img.attr('alt'));
        modal_img.attr('src', thumb.attr('src').replace(/image_page/,'high_def'));
        modal_img.attr('alt', thumb.attr('alt'));
		
		// This script will show the current picture selected in fancybox
		var idImg = $(a).attr('href');
		idImg = idImg.split('=');
		var reg = new RegExp(idImg[1],"g");
		
		$('div.gallery a').attr('href', function() {
			var chaine = ''+this;
			if(chaine.match(reg)) {
				var target = $(this);
				target.html(img);
			}
		});
		// end of the script
		
		selected.attr('rel', $(a).attr('id'));
        selected.next().find('span').html($(a).attr('rel'));
    }

    this.prevImage = function(prev) {
        var slideshow = $(prev).parents('.slideshow');
        var selected = slideshow.find('.selected');
        var img = selected.find('img');
        var modal_img = selected.next().next().find('img');
        var a = slideshow.find('#' + (parseInt(selected.attr('rel')) - 1));
		
        if (a.is('a')) {
            var thumb = $(a).children();
            var index = parseInt(a.attr('id'));
            img.attr('src', thumb.attr('src'));
            img.attr('alt', thumb.attr('alt'));
            selected.find('span').html(img.attr('alt'));
            modal_img.attr('src', thumb.attr('src').replace(/image_page/,'high_def'));
            modal_img.attr('alt', thumb.attr('alt'));
			
			var idImg = $(a).attr('href');
			idImg = idImg.split('=');
			var reg = new RegExp(idImg[1],"g");
			
			$('div.gallery a').attr('href', function() {
				var chaine = ''+this;
				if(chaine.match(reg)) {
					var target = $(this);
					target.html(img);
				}
			});
			
            selected.attr('rel', index);
            selected.next().find('span').html(a.attr('rel'));
            var carousel = slideshow.find('.carousel');
            if (carousel.children('.mpager').is('div')) {
                slideshow.find('.carousel').scrollable("seekTo", (index - 1) / 3 );
            }
        }
    }

    this.nextImage = function(next) {
        var slideshow = $(next).parents('.slideshow');
        var selected = slideshow.find('.selected');
        var img = selected.find('img');
        var modal_img = selected.next().next().find('img');
        var a = slideshow.find('#' + (parseInt(selected.attr('rel')) + 1));
        if (a.is('a')) {
            var thumb = $(a).children();
            var index = parseInt(a.attr('id'));
            img.attr('src', thumb.attr('src'));
            img.attr('alt', thumb.attr('alt'));
            selected.find('span').html(img.attr('alt'));
            modal_img.attr('src', thumb.attr('src').replace(/image_page/,'high_def'));
            modal_img.attr('alt', thumb.attr('alt'));
			
			var idImg = $(a).attr('href');
			idImg = idImg.split('=');
			var reg = new RegExp(idImg[1],"g");
			
			$('div.gallery a').attr('href', function() {
				var chaine = ''+this;
				if(chaine.match(reg)) {
					var target = $(this);
					target.html(img);
				}
			});
			
            selected.attr('rel', index);
            selected.next().find('span').html(a.attr('rel'));
            var carousel = slideshow.find('.carousel');
            if (carousel.children('.mpager').is('div')) {
                slideshow.find('.carousel').scrollable("seekTo", (index - 1) / 3 );
            }
        }
    }
    
    this.closeFancy = function()
    {
        $.fancybox.close();
    }

};

$(document).ready(function() {
    var base = /(\:3000|\:4000|\:13001|\:4103|\:4089)/;
    var _hash = location.href.indexOf('#');
    var path = location.href.split(location.hostname)[1].replace(base, '');
    var addthis_visible = false;
    
    if ( _hash == -1  && path != '/' ) {
        
        // no hash but path is not home

        // fix for traking links
        var query;
        if (path.match(/utm_/) && path.indexOf('?') > 1) {
            query = path.substr(path.indexOf('?'));
            path = path.substr(0, path.indexOf('?'));
            //console.log("path %s, query %s", path, query)
        }
        
        // redirect to swfaddress/dynamic mode (/ is reloaded without content)

        $('#content').hide();
        $('#content').append('<form id="redirect" method="post" action="/'+'#'+path+'"><input type="hidden" name="nc" value="1" /></form>');
        $('#redirect').submit();


    } else {

        // swfaddress / dynamic mode
        
        var _swf = '/';
        if ( _hash != -1 ) { _swf = location.href.substr(_hash + 1); }
        if ( (_swf != '/' && _swf != '') || ! $("#content").hasClass('loaded')) {
            preload = 0; 
            $('#content').hide();
        }

        Colette.bodyFinalize();       

        SWFAddress.addEventListener(SWFAddressEvent.CHANGE, Colette.handleChange);

        Colette.reloadStatus();

        jsReady = true;
    }
    
	$('#content').ajaxStart(function()
	{
        //$("#content").block({message: $('#ajax_loader'), css: { border:"none", backgroundColor:"transparent", color: "black"}, overlayCSS: { backgroundColor: "white", opacity: '.9' }, fadeIn:200, fadeOut:200, timeout:500});
        $(this).css('cursor', 'wait');
	});

    $('#content').ajaxStop(function()
	{
        //$("#content").unblock();
        $(this).css('cursor', 'default');
    });
});

