function checkVideo(){
    if($('#ytplayer').height()>200){
        main_boxes.init();
        //<fix>//
        try { clearTimeout(txd); } catch(ex) {};
        //</fix>//
        return;
    }
    txd=window.setTimeout("checkVideo()",500);
}

function setFooter(){
    $('#footer_container').css('top',0);
    $('#footer_container').css('top',$(document).height()+50);
}

var galleries={
    init : function(){
        $('.gallery').each(function(){
            if($(this).attr('id')=='els_brand_all'){
                window.setTimeout("galleries.start_gallery('els_brand_all')",1500);
            }
            else{
                galleries.start_gallery($(this).attr('id'));
            }
        });
    },
    start_gallery : function(el){
        $('#'+el).find('.els_gallery').cycle({
            fx:   'fade',
            speed:  1500,
            timeout: 6500,
            startingSlide: 0,
            after : function(curr,next,opts){
                galleries.set_nav(el,$('#'+el).find('.nav_gallery a').eq(opts.currSlide));
            }
        });
        $('#'+el).find('.nav_gallery a').each(function(i){
            $(this).click(function(){
                $('#'+el).find('.els_gallery').cycle(i);
                galleries.set_nav(el,$(this));
                return false;
            });
        });
        $('#'+el).find('a').attr('title','');
    },
    set_nav : function(el,linknav){
        $('#'+el).find('.nav_gallery a').each(function(){
            $(this).removeClass('on');
        });
        $(linknav).addClass('on');
    }
}

var galleries_right={
    init : function(){

        $('.gallery_r').each(function(){
            if($(this).attr('id')=='els_brand_all'){
                window.setTimeout("galleries_right.start_gallery_right('els_brand_all')",1500);
            }
            else{
                galleries_right.start_gallery_right($(this).attr('id'));
            }
        });
    },
    start_gallery_right : function(el){

        $('#'+el).find('.els_gallery').cycle({
            fx:   'fade',
            speed:  1500,
            timeout: 6500,
            startingSlide: 0,
            after : function(curr,next,opts){
                galleries_right.set_nav_right(el,$('#'+el).find('.nav_gallery_store_top a').eq(opts.currSlide));
            }
        });

        $('#'+el).find('.nav_gallery_store_top a').each(function(i){

            $(this).click(function(){
                $('#'+el).find('.els_gallery').cycle(i);
                galleries_right.set_nav_right(el,$(this));
                return false;
            });
        });
        $('#'+el).find('a').attr('title','');
    },
    set_nav_right : function(el,linknav){
        $('#'+el).find('.nav_gallery_store_top a').each(function(){
            $(this).removeClass('on');
        });
        $(linknav).addClass('on');
    }
}

var mtop={
    prev_ls : null,
    init : function(){
        $('.btn_mright').click(function(){
            mtop.mright($(this).attr('id'));
        });
        $('#become_fan>li>ul>li>a').hover(function(){
                    $(this).find('img').css('top','-27px');
                },
                function(){
                    $(this).find(' img').css('top','0');
                });
        $('#quicknav').hover(function(){},
                function(){
                    $('#quicknav').fadeOut('fast');
                });
        $('#open_qn>a').hover(function(){
                    $(this).find('img').css('top','-35px');
                },
                function(){
                    $(this).find('img').css('top','0');
                });
        $('#open_qn>a').click(function(){
            $('#quicknav').show();
        });
        $('#close_quicknav>a').click(function(){
            $('#quicknav').hide();
        });

    },
    mright	: function(elid){
        targetel=$('#'+elid).next('ul');
        type=elid.split('_');
        if($('#close_'+type[1]).is('a')) return;
        if(mtop.prev_ls!=null){
            mtop.mrigth_hide(mtop.prev_ls,$('#btn_'+mtop.prev_ls).next('ul'));
        }
				   btn_close='<a href="#" id="close_'+type[1]+'"><img src="upanddown_files/icon_close.gif" /></a>';
        $(btn_close).insertBefore($('#'+elid));
        $('#close_'+type[1]).click(function(){
            mtop.mrigth_hide(type[1],targetel);
        });
        mtop.prev_ls=type[1];
        mtop.mrigth_show(type[1],targetel);
    },
    mrigth_show : function(type,el){
        if(type=='storelocator'){
            el.show();
        }else{
            el.find('li').show();
        }
    },
    mrigth_hide : function(type,el){
        $('#close_'+type).remove();
        if(type=='storelocator'){
            el.hide();
        }else{
            el.find('li:not(.selected)').hide();
        }
    }
}

function load_fb(){
    var fb='<iframe src="http://www.facebook.com/widgets/like.php?href=www.dolcegabbana.com&amp;layout=standard&amp;show_faces=true" scrolling="no" frameborder="0" id="likethis_fb" allowtransparency="yes"></iframe>';
    $('.facebook>.p_content').append(fb);
}

function load_yt(){
    var videoId=$('#video_yt').attr('videocode');
    var params = { allowScriptAccess: "always" };
    var atts = { id: "ytplayer" };
    swfobject.embedSWF("http://www.youtube.com/v/"+videoId+"?enablejsapi=1&playerapiid=ytplayer&fs=1&showinfo=0&border=0",
            "video_yt", "350", "220", "8", null, null, params, atts);
}

function onYouTubePlayerReady(playerId) {
    shiftPosition(main_boxes.nr_items-1);
    ytplayer = document.getElementById("ytplayer");
    ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

var box_style={
    init : function(){
        $('.item').each(function(){
            box_style.setStyle($(this));
        });
    },
    setStyle: function(box) {
        var type=box.attr('class').split(' ');
        //</ix>//
        var typeSplitted = type[1].split('_');
        if (!typeSplitted[1]) return;
        var column=typeSplitted[1].substr(0,3);
        //</fix>//

        if(!type[2]){
            //$(this).find('.imglink').attr('title','');
            box.hover(
                    function(){
                        box_style.show($(this).attr('id'));
                    },
                    function(){
                        box_style.hide($(this).attr('id'));
                    });
        }
    },
    show : function(id){
        var box=$('#'+id);
        var type=box.attr('class').split(' ');
        var column=type[1].split('_')[1].substr(0,3);

        column!=170 ? ico_godetail='<img src="img/shared/ico_godetail.gif" />' : ico_godetail='<img src="img/shared/ico_godetail_170.png" />';
        var url=box.find('.p_content a.imglink').attr('href');

        var theImg=box.find('.p_content a.imglink');
        var fdr_height=box.find('.p_content a.imglink>img').height();
        var fdr_width=box.find('.p_content a.imglink>img').width();
        var icodetail='<div id="ico_godetail_'+column+'"><a href="'+url+'">'+ico_godetail+'</a></div>';
        var fdr='<div id="fdr_boxes">&nbsp;</div>';
        theImg.append(fdr);
        $('#fdr_boxes').css('height',fdr_height);
        $('#fdr_boxes').css('width',fdr_width);
        $('#fdr_boxes').fadeTo('fast',0.1);
        if(column==170){
            $('#'+id).find('.p_content').append(icodetail);
            $('#'+id).find('.txt_box_vis').attr('class','txt_box_vis_on');
        }
        if(box.find('.txt_box').is('div')){
            $('#'+id).find('.txt_box').append(icodetail);
            box.find('.txt_box').width(box.width()-75);
            box.find('.txt_box').show();
        }
    },
    hide : function(id){
        var box=$('#'+id);
        var type=box.attr('class').split(' ');
        var column=type[1].split('_')[1].substr(0,3);
        box.find('#ico_godetail_'+column).remove();
        box.find('#fdr_boxes').remove();
        box.find('.txt_box_vis_on').attr('class','txt_box_vis');
        if(box.find('.txt_box').is('div')){
            box.find('.txt_box').hide();
        }
    }
}

var main_boxes={
    nr_items : 0,
    init : function(){
        main_boxes.nr_items=$('#container_boxes>.item').length;
        $('#container_boxes>.item').each(function(i){
            $(this).attr('id','item_'+i);
            $(this).find('a').attr('title','');
            if(i==main_boxes.nr_items-1){
                shiftPosition(i);
            }
        });
        checkRightBoxes();
    }
}

Array.max = function(array){
    return Math.max.apply( Math, array );
};
var leftpos=[];

function checkRightBoxes(){
    maxLeft=Array.max(leftpos);
    if(maxLeft<550){
        $('#nav_top_left').css('width',840);
    }
    else{
        $('#nav_top_left').css('width',890);
    }

    $('#open_qn').css('left',maxLeft+30);
    $('#nav_top_right').css('left',maxLeft+30);
    $('#footer_container').css('width',maxLeft+170);
    $('#c_cols_qn').css('width',maxLeft+170);
    leftpos=[];
}

String.prototype.startsWith = function(string) {
    return this.match("^" + string) == string;
}

function fb_photolink(){
    //<fix>
    $('.facebook a').each(function() {
        var href = $(this).attr("href") || "";
        if (href.startsWith("/photo.php")) {
            var link = $(this);
            var href= link.attr('href');
            link.attr('href', 'http://www.facebook.com' + href);
            link.attr('target', '_blank');
        }
    });
    //</fix>
}

function TopLink(linkUrl, linkText) {
   this.href = linkUrl || "";
   this.text = linkText || "";
}
function TopGallery() {
    this.boxes =  {
        'left'  : {'links' : []},
        'right' : {'links' : []}
    };

    this.get = function(index) {
        if (index >= 0) {
            for (var key in this.boxes) {
                if (index-- <= 0) {
                    return this.boxes[key];
                }
            }
        }

        return null;
    }

    this.addLink = function(box, linkUrl, linkText) {
        this.boxes[box].links.push({'href': linkUrl, 'text' : linkText});
    }

    this.emptyLinks = function() {
        var linksCount = 0;
        for (var key in this.boxes) {
            linksCount += this.boxes[key].links.length;
        }
        return (linksCount <= 0);
    }
}



$(function() {
    var galleryR = $(".gallery_r");
    $.each(galleryR, function(index, value) {
        var gallery = topGalleries[lang];

        if ((!gallery) || (gallery.emptyLinks())) {
           gallery = topGalleries["en"];
        }

        var box = gallery.get(index);
        var links = box.links;

        $(value).find(".els_gallery li").each(function() {
            $.each($(this).find("p a[target=_blank]"), function(index, value) {
                if (!links[index]) return;

                var link = $(value);
                with(links[index]) {
                    link.attr({"href": href, "title": href});
                    if (!link.parents(".pic_brand:first").is("p")) {
                        link.html(text);
                    }
                }
            });
        });
    });
});

$(document).ready(function(){
    mtop.init();
    fb_photolink();
});

function BoxManager() {
    var margin = 10;
    var container = $("#container_boxes")
    var center    = $("#center_boxes");
    var box       = $("#item_0");
    var layout    = $("#layout");

    this.delegate = new shiftPosition();

    this.detachFromContainer = function(index) {
        var removeId = "item_" + index;
        var boxes = new Array();
        boxes = $.grep(this.delegate.pushed_ar, function(value) {
            return value != removeId;
        });

        this.delegate.pushed_ar = boxes;
    }

    this.centerBoxes = function() {
        return center.find(" > div");
    }


    this.centerWidth = function() {
        var width = 0;
        var centerBoxes = this.centerBoxes();

        centerBoxes.each(function() {
            width += $(this).width();
        });

        // margine sx
        width += + (margin * (centerBoxes.length - 1));

        return width;
    }

    this.centerPlusOneBoxWidth = function() {
        return this.centerWidth() + box.width() + margin;
    }

    this.target = function() {
        var centerBoxes = this.centerBoxes();
        var canAdd = this.centerPlusOneBoxWidth() <= layout.width();

        if ((centerBoxes.length == 2) && (canAdd)) {
            return "center";
        }

        if ((centerBoxes.length == 3) && (!canAdd)) {
            return "container";
        }

        return "";
    }

    this.moveBox = function(target) {

        switch(target) {
            case "center":
                var newBox = box.clone();
                newBox.removeAttr("id")
                newBox.removeAttr("style");
                newBox.css({"margin-left": margin + "px", "class": box.attr("class")});
                newBox.attr("id", "center_2");

                this.detachFromContainer(0);

                center.css({width: this.centerPlusOneBoxWidth() + "px"});

                box.remove();

                main_boxes.nr_items -= 1;

                center.append(newBox);

                box_style.setStyle(newBox);

                this.delegate = new shiftPosition();
                break;
            case "container":
                var newBox = center.find(">div:last");
                newBox.removeAttr("style");

                container.prepend(newBox);

                center.css({width: this.centerWidth() + "px"});

                main_boxes.init();

                this.delegate = new shiftPosition();
                break;
        }
    }
}

$(window).load(function(){
    main_boxes.init();
    galleries.init();
    galleries_right.init();
    if($('.facebook').is('div')){
        load_fb();
    }
    if($('#video_yt').is('div')){
        load_yt();
    }
    box_style.init();
    $('#footer_container').css('top',$(document).height()+60);


    $(window).resize(function(){
        var manager = new BoxManager();
        manager.moveBox(manager.target());

        window.setTimeout("shiftPosition()",200);
        window.setTimeout("setFooter()",200);
        window.setTimeout("checkRightBoxes()",200);
    });

    $(window).resize();
    checkVideo();
});

